前言
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HTTP和浏览器有点像,但却不是浏览器。很多人觉得既然HttpClient是一个HTTP客户端编程工具,很多人把他当做浏览器来理解,但是其实HttpClient不是浏览器,它是一个HTTP通信库,因此它只提供一个通用浏览器应用程序所期望的功能子集,最根本的区别是HttpClient中没有用户界面,浏览器需要一个渲染引擎来显示页面,并解释用户输入。HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息。
简介
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
下载地址: Apache HttpComponents – HttpComponents Downloads
相关依赖
httpClient的依赖,这里用的是4.5版本的。注意4.4版本以下的httpClient(俗称旧版)会有些许不同。
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.12</version>
</dependency>
当然还有json依赖和testng等
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<!-- <scope>test</scope> -->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
使用方法
一个完整的httpClient连接,有5个部分组成。
1.连接的定义,设置最大连接数,最大连接超时时间,最大读取超时时间,最大返回超时时间等。可以为空。
2.请求方式,post,get等。
3.请求地址,url地址。
4.请求的参数,form表单,json等。可以为空。
5.响应内容,response返回。返回后关闭连接。
一个简单的httpClient连接例子
/**
* @param url
* @return get请求url,以String形式返回请求结果
*/
public String httpGetRequest(String url) {
HttpGet httpGet = new HttpGet(url);
System.out.println(url);
CloseableHttpClient httpClient = HttpClients.custom().build();
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
System.out.println("--------------------------------------");
System.out.println(result);
System.out.println("--------------------------------------");
response.close();
return result;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
连接的定义
定义连接在CloseableHttpClient httpClient = HttpClients.custom().build();中进行。上面的例子,定位为空,可以加上如下定义
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", createSSLConnSocketFactory()).build();
// 设置连接池
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 设置连接池大小
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(cm.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(600000);
// 设置读取超时
configBuilder.setSocketTimeout(600000);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(600000);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
如果是https的连接,则需求创建ssl安全连接。我们可以重写证书认证方法的形式绕过认证。设置加在
Registry socketFactoryRegistry = RegistryBuilder.create().register(“http”, PlainConnectionSocketFactory.INSTANCE).register(“https”, createSSLConnSocketFactory()).build();
Ssl方法如下
/**
* 创建SSL安全连接
*
* @return SSLConnectionSocketFactory
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext ctx = SSLContext.getInstance("SSL");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
sslsf = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}
请求的方式
Get请求方式HttpGet httpGet = new HttpGet(url);
Post请求方式HttpPost httpPost = new HttpPost(url);
请求参数
JSON传参方式,以json字符串的方式传参,(传入参数String url,String json)
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, UTF_8);// 解决中文乱码问题
entity.setContentEncoding(UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
form表单传参方式,以键值对params的方式传参,单独处理url,(传入参数String url,Map<String,Object> params)
URIBuilder ub = new URIBuilder(url);
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
请求加入headers,(传入参数Map<String,Object> headers)
for (Map.Entry<String, Object> header : headers.entrySet()) {
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
响应内容
接口返回的内容以字符串的形式处理。
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
System.out.println("--------------------------------------");
System.out.println(result);
System.out.println("--------------------------------------");
response.close();
return result;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
获取cookie,需求在httpClient中setCookieStore,然后get出来。
BasicCookieStore setCookieStore = new BasicCookieStore();
client = HttpClients.custom().setDefaultCookieStore(setCookieStore).setConnectionManager(cm).build();
cookieStore = setCookieStore;
// 获取cookie
public static String cookies(HttpRequestBase request) {
String cookie = null;
CloseableHttpClient httpClient = getHttpClient();
try {
// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
List<Cookie> cookieList = cookieStore.getCookies();
StringBuffer tmpcookies = new StringBuffer();
for (Cookie c : cookieList) {
String name = c.getName();
String value = c.getValue();
tmpcookies.append(name + "=" + value + ";");
}
response.close();
cookie = tmpcookies.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return cookie;
}
本人用到的HttpClientUtils
package httpClientUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
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 zetar.api.UploadBean;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
private static PoolingHttpClientConnectionManager cm;
private static String EMPTY_STR = "";
private static String UTF_8 = "UTF-8";
private static CloseableHttpClient client;
private static final int MAX_TIMEOUT = 600000;
protected static String scheme = "";
protected static String host = "";
private static BasicCookieStore cookieStore;
// 设置scheme协议和host域名,要改动的时候,继承并重写这个方法就好了
protected void set() throws UnsupportedEncodingException, URISyntaxException {
// scheme = "https";
// host = "www.baidu.com";
}
// 初始化连接池
private static void init() {
if (cm == null) {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", createSSLConnSocketFactory()).build();
// 设置连接池
cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 设置连接池大小
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(cm.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
}
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext ctx = SSLContext.getInstance("SSL");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
sslsf = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}
/**
* 通过连接池 获取需要安全认证的httpClient的实例
*
**/
private static CloseableHttpClient getHttpClient() {
init();
if (client != null) {
return client;
}
BasicCookieStore setCookieStore = new BasicCookieStore();
client = HttpClients.custom().setDefaultCookieStore(setCookieStore).setConnectionManager(cm).build();
cookieStore = setCookieStore;
return client;
}
// 重置httpClient连接
public static void releaseInstance() {
client = null;
}
// map转成名值对list
private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
return pairs;
}
/**
* 处理Http请求
*/
protected static String getResult(HttpRequestBase request) {
// CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = getHttpClient();
try {
CloseableHttpResponse response = httpClient.execute(request);
// response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
// long len = entity.getContentLength();// -1 表示长度未知
String result = EntityUtils.toString(entity, UTF_8);
// System.out.println("--------------------------------------");
// System.out.println(result);
// System.out.println("--------------------------------------");
response.close();
// httpClient.close();
return result;
}
} catch (IOException e) {
e.printStackTrace();
}
return EMPTY_STR;
}
// 获取cookie
public static String cookies(HttpRequestBase request) {
String cookie = null;
CloseableHttpClient httpClient = getHttpClient();
try {
// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// System.out.println("http client success!");
List<Cookie> cookieList = cookieStore.getCookies();
StringBuffer tmpcookies = new StringBuffer();
for (Cookie c : cookieList) {
String name = c.getName();
String value = c.getValue();
tmpcookies.append(name + "=" + value + ";");
}
response.close();
cookie = tmpcookies.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return cookie;
}
/*
* 下面是请求scheme(http/https)协议,加host域名,加path接口地址的方法
*/
/**
* @param path
* @return get请求path,以String形式返回请求结果
* @throws URISyntaxException
*/
public static String getRequest(String path) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpGet httpGet = new HttpGet(ub.build());
System.out.println(ub);
return getResult(httpGet);
}
// 带参数的get请求path,以String形式返回请求结果
public static String getRequest(String path, Map<String, Object> params) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
System.out.println(ub);
return getResult(httpGet);
}
// 带请求头和参数的get请求path,以String形式返回请求结果
public static String getRequest(String path, Map<String, Object> headers, Map<String, Object> params)
throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
System.out.println(ub);
return getResult(httpGet);
}
// 带请求头的get请求path,以String形式返回请求结果
public static String getRequestAddHeaders(String path, Map<String, Object> headers) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpGet httpGet = new HttpGet(ub.build());
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
System.out.println(ub);
return getResult(httpGet);
}
// post请求path,以String形式返回请求结果
public static String postRequest(String path) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpPost httpPost = new HttpPost(ub.build());
System.out.println(ub);
return getResult(httpPost);
}
// 传json参数的post请求path,以String形式返回请求结果
public static String postRequest(String path, String json) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpPost httpPost = new HttpPost(ub.build());
StringEntity entity = new StringEntity(json, UTF_8);// 解决中文乱码问题
entity.setContentEncoding(UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println(ub);
return getResult(httpPost);
}
// 带请求头传json参数的post请求path,以String形式返回请求结果
public static String postRequest(String path, Map<String, Object> headers, String json) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpPost httpPost = new HttpPost(ub.build());
for (Map.Entry<String, Object> header : headers.entrySet()) {
httpPost.addHeader(header.getKey(), String.valueOf(header.getValue()));
}
StringEntity entity = new StringEntity(json, UTF_8);// 解决中文乱码问题
entity.setContentEncoding(UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println(ub);
// System.out.println(json);
return getResult(httpPost);
}
// 传form表格参数的post请求path,以String形式返回请求结果
public static String postRequest(String path, Map<String, Object> params)
throws UnsupportedEncodingException, URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpPost httpPost = new HttpPost(ub.build());
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
System.out.println(ub);
return getResult(httpPost);
}
// 传form表格参数的post请求path,以String形式返回请求结果
public static String postRequestAndHeaders(String path, Map<String, Object> headers)
throws UnsupportedEncodingException, URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpPost httpPost = new HttpPost(ub.build());
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
System.out.println(ub);
return getResult(httpPost);
}
// 传form表格参数的post请求path,以String形式返回cookie
public static String postCookie(String path, Map<String, Object> params)
throws UnsupportedEncodingException, URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpPost httpPost = new HttpPost(ub.build());
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
System.out.println(ub);
return cookies(httpPost);
}
// 带域账号密码权限,传form表格参数的post请求path,以String形式返回cookie
public static String postCookie(String path, Map<String, Object> params, String AuthorizationUserName,
String AuthorizationPassword) throws UnsupportedEncodingException, URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
String encoding = DatatypeConverter
.printBase64Binary((AuthorizationUserName + ":" + AuthorizationPassword).getBytes("UTF-8"));
HttpPost httpPost = new HttpPost(ub.build());
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
httpPost.setHeader("Authorization", "Basic " + encoding);
System.out.println(ub);
return cookies(httpPost);
}
// 带域账号密码权限,传form表格参数的post请求path,以String形式返回cookie
public static Map<String, Object> postHeaders(String path, Map<String, Object> params, String AuthorizationUserName,
String AuthorizationPassword) throws UnsupportedEncodingException, URISyntaxException {
Map<String, Object> headers = new HashMap<>();
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
String encoding = DatatypeConverter
.printBase64Binary((AuthorizationUserName + ":" + AuthorizationPassword).getBytes("UTF-8"));
HttpPost httpPost = new HttpPost(ub.build());
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
httpPost.setHeader("Authorization", "Basic " + encoding);
System.out.println(ub);
String cookie = cookies(httpPost);
headers.put("Cookie", cookie);
headers.put("Authorization", "Basic " + encoding);
return headers;
}
// 带请求头传form表格参数的post请求path,以String形式返回请求结果
public static String postRequest(String path, Map<String, Object> headers, Map<String, Object> params)
throws UnsupportedEncodingException, URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setScheme(scheme);
ub.setHost(host);
ub.setPath(path);
HttpPost httpPost = new HttpPost(ub.build());
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
System.out.println(ub);
return getResult(httpPost);
}
/*
* 以下为直接请求完整URL的方法
*/
/**
* @param url
* @return get请求url,以String形式返回请求结果
*/
public static String httpGetRequest(String url) {
HttpGet httpGet = new HttpGet(url);
System.out.println(url);
return getResult(httpGet);
}
// 带请求头和参数的get请求url,以String形式返回请求结果
public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
throws URISyntaxException {
URIBuilder ub = new URIBuilder(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
System.out.println(ub);
return getResult(httpGet);
}
// 带参数的get请求url,以String形式返回请求结果
public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
URIBuilder ub = new URIBuilder(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
System.out.println(ub);
return getResult(httpGet);
}
// 带请求头和参数的get请求url,以String形式返回请求结果
public static String httpGetRequestAddHeaders(String url, Map<String, Object> headers) throws URISyntaxException {
HttpGet httpGet = new HttpGet(url);
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
System.out.println(url);
return getResult(httpGet);
}
// post请求url,以String形式返回请求结果
public static String httpPostRequest(String url) {
HttpPost httpPost = new HttpPost(url);
System.out.println(url);
return getResult(httpPost);
}
// 传json参数的post请求url,以String形式返回请求结果
public static String httpPostRequest(String url, String json) {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, "utf-8");// 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println(url);
return getResult(httpPost);
}
// 传form表格参数的post请求url,以String形式返回请求结果
public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
System.out.println(url);
return getResult(httpPost);
}
// 带请求头传form表格参数的post请求url,以String形式返回请求结果
public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
System.out.println(url);
return getResult(httpPost);
}
// 传form表格参数的post请求url,以String形式返回cookie
public static String httpPostCookie(String url, Map<String, Object> params)
throws UnsupportedEncodingException, URISyntaxException {
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
System.out.println(url);
return cookies(httpPost);
}
// 带域账号密码权限,传form表格参数的post请求url,以String形式返回cookie
public static Map<String, Object> httpPostHeaders(String url, Map<String, Object> params,
String AuthorizationUserName, String AuthorizationPassword)
throws UnsupportedEncodingException, URISyntaxException {
Map<String, Object> headers = new HashMap<>();
HttpPost httpPost = new HttpPost(url);
String encoding = DatatypeConverter
.printBase64Binary((AuthorizationUserName + ":" + AuthorizationPassword).getBytes("UTF-8"));
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
httpPost.setHeader("Authorization", "Basic " + encoding);
System.out.println(url);
String cookie = cookies(httpPost);
headers.put("Cookie", cookie);
headers.put("Authorization", "Basic " + encoding);
return headers;
}
// 带请求头传json参数的post请求url,以String形式返回请求结果
public static String httpPostRequest(String url, Map<String, Object> headers, String json)
throws URISyntaxException {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, Object> header : headers.entrySet()) {
httpPost.addHeader(header.getKey(), String.valueOf(header.getValue()));
}
StringEntity entity = new StringEntity(json, UTF_8);// 解决中文乱码问题
entity.setContentEncoding(UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println(url);
// System.out.println(json);
return getResult(httpPost);
}