apache org doc :http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e49

依赖:

<!--  https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency> <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
</dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext; import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.log4j.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost; import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; public class HttpDemo {
private static Logger LOGGER = Logger.getLogger(HttpDemo.class);
private static CloseableHttpResponse response;
private static HttpEntity entity; /**
* this is ssl ignore https CloseableClient
*/
static CloseableHttpClient sslIgnoreClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
CloseableHttpClient client = null;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); return client;
} /**
* http get method
*/
static String doGet(String url, Map<Object, Object> header) throws KeyStoreException, IOException,
KeyManagementException, NoSuchAlgorithmException {
String result = null; // initialize result
CloseableHttpClient request = sslIgnoreClient();
HttpGet msg = new HttpGet(url);
if (header != null) {
header.forEach((key, value) -> {
msg.addHeader(key.toString(), value.toString());
}); }
response = request.execute(msg);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
}
return result;
} /**
* String body is json type
*/
static String doPost(String url, String body, Map<Object, Object> header) throws KeyStoreException, IOException,
KeyManagementException, NoSuchAlgorithmException {
String result = null;
CloseableHttpClient request = sslIgnoreClient();
HttpPost msg = new HttpPost(url);
if (header != null) {
header.forEach((key, value) -> {
msg.addHeader(key.toString(), value.toString());
});
}
msg.setEntity(new StringEntity(body));
response = request.execute(msg);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
}
return result;
} /**
* do post form-data
*/
static String doPostParam(String url, Map<Object, Object> header, Map<Object, Object> params) throws KeyStoreException, IOException,
KeyManagementException, NoSuchAlgorithmException {
String result = null;
CloseableHttpClient request = sslIgnoreClient();
HttpPost msg = new HttpPost();
if (header != null) {
header.forEach((key, value) -> {
msg.addHeader(key.toString(), value.toString());
});
}
List<BasicNameValuePair> paramList = new ArrayList<>();
params.forEach((key, value) -> {
paramList.add(new BasicNameValuePair(key.toString(), value.toString()));
});
HttpEntity formEntity = new UrlEncodedFormEntity(paramList, "utf-8");
msg.setEntity(formEntity);
response = request.execute(msg);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
}
return result;
} /**
* do upload and download operation
*/
static String postFileImage(String url, Map<Object, Object> textBody, List<String> fileList, Map<Object, Object> header, int ttl) throws KeyStoreException, IOException,
KeyManagementException, NoSuchAlgorithmException {
String result = null;
CloseableHttpClient request = sslIgnoreClient();
HttpPost msg = new HttpPost();
//msg.setHeader(key,value);
if (header != null) {
header.forEach((key, value) -> {
msg.addHeader(key.toString(), value.toString());
});
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(ttl).setSocketTimeout(ttl).build();
msg.setConfig(requestConfig);
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); fileList.forEach(item -> {
File f = new File(item);
try {
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}); textBody.forEach((key, value) -> {
builder.addTextBody(String.valueOf(key), String.valueOf(value), ContentType.TEXT_PLAIN);
}); msg.setEntity(builder.build());
response = request.execute(msg);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
long length = entity.getContentLength();
byte[] res = null;
res = EntityUtils.toByteArray(entity);
result = new String(res, StandardCharsets.UTF_8);
} return result; } }

  

org.apache.httpcomponents.httpclient的更多相关文章

  1. httpclient工具使用(org.apache.httpcomponents.httpclient)

    httpclient工具使用(org.apache.httpcomponents.httpclient) 引入依赖 <dependency> <groupId>org.apac ...

  2. org.apache.httpcomponents httpclient 发起HTTP JSON请求

    1. pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactI ...

  3. org.apache.httpcomponents:httpclient 工具类

    基于httpclient 版本4.4.1 因为http连接需要三次握手,在需要频繁调用时浪费资源和时间 故采用连接池的方式连接 根据实际需要更改  连接池最大连接数.路由最大连接数 另一个需要注意的是 ...

  4. org.apache.commons.httpclient工具类

    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpcl ...

  5. JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例

    一.简述需求 平时我们需要在JAVA中进行GET.POST.PUT.DELETE等请求时,使用第三方jar包会比较简单.常用的工具包有: 1.https://github.com/kevinsawic ...

  6. org.apache.commons.httpclient工具类(封装的HttpUtil)

    import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java ...

  7. Apache HttpComponents Client 4.0快速入门/升级-2.POST方法访问网页

    Apache HttpComponents Client 4.0已经发布多时,httpclient项目从commons子项目挪到了HttpComponents子项目下,httpclient3.1和 h ...

  8. Apache HttpComponents中的cookie匹配策略

    Apache HttpComponents中的cookie匹配策略 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre. ...

  9. org.apache.commons.httpclient和org.apache.http.client区别(转)

    官网说明: http://hc.apache.org/httpclient-3.x/ Commons HttpClient项目现已结束,不再开发.它已被其HttpClient和HttpCore模块中的 ...

随机推荐

  1. javascript控制台 js的调试

    一.错误查询,按F12键,点击控制台.

  2. 【vue 权威指南】 学习笔记 二

    1.指令 1.1内部指令 基础指令:v-show , v-else , v-model , v-repeat , v-for , v-text , v-el , v-html , v-on , v-b ...

  3. Selenium chromeDriver启动时报错:session not created: This version of ChromeDriver only supports Chrome

    解决方案: 这是因为ChromeDriver与本地chrome浏览器的版本不一致导致 ChromeDriver下载地址:http://npm.taobao.org/mirrors/chromedriv ...

  4. hadoop 配置信息记录

    ssh-keygen  -t   rsa   -P  '' 192.168.157.148 hadoop01192.168.157.149 hadoop02 mkdir  /root/hadoopmk ...

  5. 【转】Java Future 怎么用 才算是真正异步

    接着上一篇继续并发包的学习,本篇说明的是Callable和Future,它俩很有意思的,一个产生结果,一个拿到结果.        Callable接口类似于Runnable,从名字就可以看出来了,但 ...

  6. python爬取连续一字板股票及当时日期数据【原创分享】

    本篇为个人测试记录,记录爬取连续一字板的股票及当时日期. import tushare as ts import pandas as pd import time # 筛选一字板的策略 def gp_ ...

  7. SpringBoot学习- 4、整合JWT

    SpringBoot学习足迹 1.Json web token(JWT)是为了网络应用环境间传递声明而执行的一种基于JSON的开发标准(RFC 7519),该token被设计为紧凑且安全的,特别适用于 ...

  8. AntDesign(React)学习-13 Warning XX should not be prefixed with namespace XXX

    有篇UMI入门简易教程可以看看:https://www.yuque.com/umijs/umi/hello 程序在点击操作时报了一个Warning: [sagaEffects.put] User/up ...

  9. OSI协议

    物理层: 网线连接在客户端计算机上,其实是连接在了计算机的一个叫做网卡的设备上,网卡是专门负责与外界通信的.网线一般是双绞线或者光缆,也可以使用无线电波,中间经过交换机,路由器,防火墙等等一堆设备统称 ...

  10. Codeforces Round #614 (Div. 2) C - NEKO's Maze Game

    题目链接:http://codeforces.com/contest/1293/problem/C 题目:给定一个 2*n的地图,初始地图没有岩浆,都可以走, 给定q个询问,每个询问给定一个点(x,y ...