HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

1.引入jar包

http://hc.apache.org/downloads.cgi

2.需要一个HttpClientUtils工具类

package cn.happy.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.util.*; public class HttpClientUtils { private static PoolingHttpClientConnectionManager connectionManager = null;
private static HttpClientBuilder httpBuilder = null;
private static RequestConfig requestConfig = null; private static int MAXCONNECTION = 10; private static int DEFAULTMAXCONNECTION = 5; private static String IP = "cnivi.com.cn";
private static int PORT = 80; static {
//设置http的状态参数
requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build(); HttpHost target = new HttpHost(IP, PORT);
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(MAXCONNECTION);//客户端总并行链接最大数
connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);//每个主机的最大并行链接数
connectionManager.setMaxPerRoute(new HttpRoute(target), 20);
httpBuilder = HttpClients.custom();
httpBuilder.setConnectionManager(connectionManager);
} public static CloseableHttpClient getConnection() {
CloseableHttpClient httpClient = httpBuilder.build();
return httpClient;
} public static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> e : entrySet) {
String name = e.getKey();
String value = e.getValue();
NameValuePair pair = new BasicNameValuePair(name, value);
params.add(pair);
}
HttpUriRequest reqMethod = null;
if ("post".equals(method)) {
reqMethod = RequestBuilder.post().setUri(url)
.addParameters(params.toArray(new BasicNameValuePair[params.size()]))
.setConfig(requestConfig).build();
} else if ("get".equals(method)) {
reqMethod = RequestBuilder.get().setUri(url)
.addParameters(params.toArray(new BasicNameValuePair[params.size()]))
.setConfig(requestConfig).build();
}
return reqMethod;
} public static void main(String args[]) throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put("account", "");
map.put("password", ""); HttpClient client = getConnection();
HttpUriRequest post = getRequestMethod(map, "http://cnivi.com.cn/login", "post");
HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String message = EntityUtils.toString(entity, "utf-8");
System.out.println(message);
} else {
System.out.println("请求失败");
}
}
}

3.发送Get请求

@Test
public void tGet() throws IOException {
//创建CloseableHttpClient对象,并为HttpClients赋默认值
CloseableHttpClient httpClient= HttpClients.createDefault();
//创建get请求http://www.baidu.com/ http://localhost:8080/isSelectUserto
HttpGet httpGet=new HttpGet("https://home.cnblogs.com/u/java-263/");
System.out.println("httpget的请求路径:"+httpGet.getURI());
//得到响应结果
CloseableHttpResponse httpResponse=httpClient.execute(httpGet);
//为HttpEntity创建实体
HttpEntity httpEntity=httpResponse.getEntity();
System.out.println("============================");
//打印响应状态
System.out.println( httpResponse.getStatusLine());
if (httpEntity!=null){
//打印响应内容长度
System.out.println("entity length:"+httpEntity.getContentLength());
//打印响应内容
System.out.println("entity:"+EntityUtils.toString(httpEntity,"UTF-8"));
} httpResponse.close(); httpClient.close(); }

4.发送Post请求

@Test
public void tPost() throws IOException { CloseableHttpClient httpClient=HttpClients.createDefault(); /*=============================POST请求多出的部分内容=================================================*/
HttpPost httpPost=new HttpPost("http://localhost:8080/isSelectUserto");
//创建参数队列
List<NameValuePair> list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("type","house"));
UrlEncodedFormEntity encodedFormEntity;
encodedFormEntity=new UrlEncodedFormEntity(list,"UTF-8");
/*====================================POST请求多出的部分内容==========================================*/ httpPost.setEntity(encodedFormEntity);
System.out.println("URL:"+httpPost.getURI());
/* System.out.println("entity length:"+ httpPost.getEntity().getContentLength());*/
CloseableHttpResponse httpResponse=httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
if (httpEntity!=null){
System.out.println("entity length:"+httpEntity.getContentLength());
System.out.println("Response content: " + EntityUtils.toString(httpEntity, "UTF-8"));
} httpResponse.close();
httpClient.close();
}

更多了解参考:https://blog.csdn.net/zhuwukai/article/details/78644484

最新文章

  1. LinuxStudyNote
  2. Easyui扩展icon下载
  3. CSS实现点击事件及实践
  4. C# PDFBox 解析PDF文件
  5. FZU 1914 Funny Positive Sequence
  6. IOS学习网址
  7. 正则表达式中的\n
  8. CSS样式权值
  9. poj2239 Selecting Courses --- 二分图最大匹配
  10. ubuntu上配置nginx实现反向代理
  11. Linux lvs三种模式工作原理
  12. 自己写的一个用js把select换成div与span与ul的东西
  13. PHP7 学习笔记(十四)Reids 键空间通知配合TP5 实现分布式延时任务
  14. iOS 证书申请和使用详解(详细版)阅读
  15. 读写txt
  16. visual studio 2017使用技巧
  17. Zabbix 添加主机
  18. 3.1Python的判断选择语句
  19. SuperSocket.WebSocket.WebSocketServer.Setup无法启动
  20. 做游戏的小伙伴们注意了,DDoS还可以这样破!

热门文章

  1. vue项目中编写一个图片预览的公用组件
  2. [精华][推荐]CAS SSO 单点登录框架学习 环境搭建
  3. nginx集成环境下载
  4. E:could not get lock /var/lib/dpkg/lock -ope
  5. kenlm的使用
  6. 前端学习日记之HTML、CSS 简单总结
  7. sui.js和workflow2.js内容详解
  8. Springboot &amp; Mybatis 构建restful 服务三
  9. java中如何使用break跳出多重循环
  10. 企业微信自建应用移动端动态获取li并给其事件问题总结