httpClient是java服务端可以主动发送http请求的很好用的一个轻量级工具。使用起来应该说是非常方便的。
首先在pom.xml文件中引入依赖:
<!-- HTTP访问工具httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
代码更是简洁:
CloseableHttpResponse response = null;
// 创建http连接(CloseableHttpClient是从httpclient4.3版本引进的可直接关闭释放连接的class)
CloseableHttpClient httpclient = HttpClients.createDefault();
//创建一个post请求
HttpPost post = new HttpPost("http://192.168.x.xxx:8080/login/enter.do");
try {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
post.setConfig(requestConfig);
//写入参数,有两种方法,一种是将参数逐个放入list中,另一种是拼接在一起(根据自己的需求任选一种)。
//第一种
List<NameValuePair> list = new ArrayList<>();//定义名值对列表
JSONObject obj = new JSONObject();
//把参数放到list中
list.add(new BasicNameValuePair("userName", "zhangsan"));
list.add(new BasicNameValuePair("passWord", "666"));
//把参数编码到表单实体中
HttpEntity postentity = new UrlEncodedFormEntity(list,"utf-8");
//第二种,拼接参数
/*String baseString = "userName=zhangsan&passWord=666";
StringEntity stringEntity = new StringEntity(baseString,"utf-8");
post.setEntity(stringEntity);//将请求实体放到post请求中*/
post.setEntity(postentity);//将请求实体放到post请求中
post.completed();
response = httpclient.execute(post);// 用客户端去执行post请求,返回响应
HttpEntity entity = response.getEntity();// 从响应中拿到响应实体
//收到的响应
String responseText = EntityUtils.toString(entity);
} catch (Exception e){
e.printStackTrace();
}finally{
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
if(httpclient != null){
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}