这里用httpclient4.3模拟一个表单普通文本提交的方法
建一个servlet接受表单数据,只传递2个参数,name和password
//servlet的访问地址是:http://localhost:80/testjs/servlet/FormServlet
public class FormServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取传递来的参数
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println("你输入的姓名是:"+name);
System.out.println("你输入的密码是:"+password);
//设置响应内容
response.getWriter().write(name+", 欢迎访问");
}
}
用到的jar包有:commons-codec-1.6.jar,commons-logging-1.1.3.jar,httpclient-4.3.1.jar,httpcore-4.3.jar,httpmime-4.3.1.jar
package com.test.httpClient.myTest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class TestHttpClient4 {
@Test
public void test1() throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
//post请求的url地址
HttpPost httpPost = new HttpPost("http://localhost:80/testjs/servlet/FormServlet");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
//传递2个参数 name和password
nvps.add(new BasicNameValuePair("name","王五"));
nvps.add(new BasicNameValuePair("password","12345"));
//转码 封装成请求实体
HttpEntity reqEntity = new UrlEncodedFormEntity(nvps,Consts.UTF_8);
httpPost.setEntity(reqEntity);
System.out.println("请求url地址"+httpPost.getURI());
//提交表单请求 response是表单的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity respEntity = response.getEntity();
//响应状态
System.out.println("Login form get: " + response.getStatusLine());
//EntityUtils.consume(entity);
//获取响应内容
System.out.println(EntityUtils.toString(respEntity,Charset.forName("utf-8")));
//销毁
EntityUtils.consume(respEntity);
} finally {
response.close();
}
}finally{
httpClient.close();
}
}
}
运行结果
test端
请求url地址http://localhost:80/testjs/servlet/FormServlet
Login form get: HTTP/1.1 200 OK
王五, 欢迎访问
tomcat服务器端
你输入的姓名是:王五
你输入的密码是:12345