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

使用HttpClient发送Get/Post请求 你get了吗?的更多相关文章

  1. HttpClient发送get post请求和数据解析

    最近在跟app对接的时候有个业务是微信登录,在这里记录的不是如何一步步操作第三方的,因为是跟app对接,所以一部分代码不是由我写,我只负责处理数据,但是整个微信第三方的流程大致都差不多,app端说要传 ...

  2. 使用httpClient发送get\post请求

    maven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId&g ...

  3. 在ASP.NET Core中用HttpClient(三)——发送HTTP PATCH请求

    在前面的两篇文章中,我们讨论了很多关于使用HttpClient进行CRUD操作的基础知识.如果你已经读过它们,你就知道如何使用HttpClient从API中获取数据,并使用HttpClient发送PO ...

  4. 使用httpclient发送get或post请求

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

  5. 【JAVA】通过HttpClient发送HTTP请求的方法

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...

  6. Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  7. Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  8. httpclient 发送一个请求

    httpclient版本 4.1 发送一个post请求 public static JSONObject post(String url,JSONObject json){ HttpClient cl ...

  9. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

随机推荐

  1. weblogic安装升级配置

    本次操作是主要围绕如何搭建weblogic服务器升级weblogic软件及配置服务,总共有三大步骤,可划分为六个小步骤: 选取已有环境,准备weblogic压缩包,java包等 准备操作系统环境用户目 ...

  2. 代码简洁的滑动门(tab)jquery插件

    < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org ...

  3. 茶杯头开枪ahk代码

    ;说明这个工具是为了茶杯头写的,F1表示换枪攻击,F3表示不换枪攻击,F2表示停止攻击. $F1::loop{ GetKeyState, state, F2, Pif state = D{break ...

  4. 【转】Android总结篇系列:Activity启动模式(lauchMode)

    [转]Android总结篇系列:Activity启动模式(lauchMode) 本来想针对Activity中的启动模式写篇文章的,后来网上发现有人已经总结的相当好了,在此直接引用过来,并加上自己的一些 ...

  5. C# 使用System.Speech 进行语音播报和识别

    C# 使用System.Speech 进行语音播报和识别 using System.Speech.Synthesis; using System.Speech.Recognition; //语音识别 ...

  6. etcd 增减节点

    一.查看集群节点 etcdctl --endpoint=https://10.2.0.6:2379 --ca-file=/etc/etcd/ca.pem --cert-file=/etc/etcd/c ...

  7. qt字符数组转ASCII(十六进制)

    接收网络传输数据 QByteArray  array;//显示字符串 QString str = QString::fromLocal8Bit(array); m_receiveTxt.append( ...

  8. Git使用(二、分支的创建和上传)

    介绍使用TortoiseGit创建分支并push到gitlab项目库,转载请注明出处. 一.创建一个新的文件夹,把要待编辑的工程从gitlab上pull到该文件夹. 其中URL从gitlab的对应项目 ...

  9. spring扩展点总结

    NamespaceHandler 通过自定义的NamespaceHandler,配合BeanDefinitionParser,可以完成自定义Bean的组装操作,对于BeanDefinition的数据结 ...

  10. 5随机到7随机的C++实现

    一.5随机到7随机 //给定条件 int Rand1To5(){ + ; } //实现代码,使用插空法和筛的过程 int Rand1To7(){ ; do{ tmp = (Rand1To5() - ) ...