常用的http调用接口的方式:post, get,put
参数格式:jsonString,键值对(冒号的json,等于号的键值对)
HTTP请求工具类:
package com.api.wght.util;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings("deprecation")
public class HTTPUtil {
private Logger logger = LoggerFactory.getLogger(getClass());
public static final int Format_KeyValue = 0;
public static final int Format_Json = 1;
/**
* 创建HttpClient客户端
*
* @param isHttps
* @return
*/
public CloseableHttpClient createClient(boolean isHttps) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
if (isHttps) {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClientBuilder.setSSLSocketFactory(sslsf);
} catch (Exception e) {
logger.error("创建HTTPS客户端异常");
e.printStackTrace();
}
}
return httpClientBuilder.build();
}
/**
* 调用Get接口
*
* @param url 接口地址
* @return
*/
public String sendGet(String url,boolean isHttps) {
return sendGet(url, createClient(isHttps));
}
/**
* 有超时限制
* @param url
* @param isHttps
* @param timeout
* @return
*/
public String sendGet(String url, boolean isHttps, Integer timeout) {
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpGet request = null;
try {
CloseableHttpClient httpClient = createClient(isHttps);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
request = new HttpGet(url);
//设置超时
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
request.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
e.printStackTrace();
return "";
}
return null;
}
/**
* 调用Get接口
*
* @param url 接口地址
* @param httpClient
* @return
*/
public String sendGet(String url, CloseableHttpClient httpClient) {
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpGet request = null;
try {
request = new HttpGet(url);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
CloseableHttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
e.printStackTrace();
} finally {
if (request != null)
request.releaseConnection();
}
return null;
}
/**
* 调用Post接口
*
* @param url 接口地址
* @param params 参数
* @param type 参数类型,0:键值对,1:json数据
* @param httpClient
* @return
*/
public String sendPost(String url, String parameters, int type, CloseableHttpClient httpClient) {
//logger.info("type:"+type);
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpPost request = null;
try {
request = new HttpPost(url);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
StringEntity entity = new StringEntity(parameters, "UTF-8");
if (type == Format_KeyValue) {
logger.info("11111111");
// request.addHeader("Content-Type", "application/x-www-form-urlencoded");
entity.setContentType("application/x-www-form-urlencoded");
} else if (type == Format_Json) {
// request.addHeader("Content-Type", "application/json");
entity.setContentType("application/json");
} else {
logger.error("不支持的参数格式");
return null;
}
request.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
e.printStackTrace();
} finally {
if (request != null)
request.releaseConnection();
}
return null;
}
/**
* 调用Post接口,参数为键值对方式
*
* @param url 接口地址
* @param params 键值对参数
* @return
*/
public String sendPostByKeyValue(String url, Map params,boolean isHttps) {
return sendPostByKeyValue(url, params, createClient(isHttps));
}
/**
* 调用Post接口,参数为键值对方式
*
* @param url 接口地址
* @param params 键值对参数
* @param httpClient
* @return
*/
public String sendPostByKeyValue(String url, Map params, CloseableHttpClient httpClient) {
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpPost request = null;
try {
request = new HttpPost(url);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
List nvps = new ArrayList();
for (Map.Entry entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
request.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
e.printStackTrace();
} finally {
if (request != null)
request.releaseConnection();
}
return null;
}
public String doPostData(String url, Map paramMap, Map headerData, byte[] stream,boolean isHttps) {
return doPostData( url, paramMap, headerData, stream,createClient(isHttps));
}
/**
* 调用http接口传输文件
* @param url
* @param paramMap
* @param headerData
* @param stream
* @param httpClient
* @return
*/
public String doPostData(String url, Map paramMap, Map headerData, byte[] stream, CloseableHttpClient httpClient) {
CloseableHttpResponse response = null;
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpPost request = null;
try {
request = new HttpPost(url);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for(Map.Entry param : paramMap.entrySet()){
builder.addTextBody(param.getKey(), param.getValue().toString(), ContentType.TEXT_PLAIN);
}
builder.addBinaryBody("file",stream,ContentType.APPLICATION_OCTET_STREAM,paramMap.get("fileName").toString());
HttpEntity reqEntity = builder.build();
request.setEntity(reqEntity);
response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
e.printStackTrace();
} finally {
try {
if (response != null){
response.close();
}if(request!=null) {
request.releaseConnection();
}
}catch (IOException e){
logger.error("关闭链接出错:"+e.getMessage());
}
}
return null;
}
/**
* 调用Post接口,参数为JSON格式
*
* @param url 接口地址
* @param params json数据
* @return
*/
public String sendPostByJson(String url, String params,boolean isHttps) {
return sendPost(url, params, Format_Json, createClient(isHttps));
}
/**
* 调用Post接口,参数为JSON格式
*
* @param url 接口地址
* @param params json数据
* @param httpClient
* @return
*/
public String sendPostByJson(String url, String params, CloseableHttpClient httpClient) {
return sendPost(url, params, Format_Json, httpClient);
}
public String sendPutByJson (String url, String token, String jsonStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
httpPut.setConfig(requestConfig);
httpPut.setHeader("Content-type", "application/json");
httpPut.setHeader("DataEncoding", "UTF-8");
httpPut.setHeader("token", token);
CloseableHttpResponse httpResponse = null;
try {
httpPut.setEntity(new StringEntity(jsonStr));
httpResponse = httpClient.execute(httpPut);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
return result;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/* public String sendPut (String url,String parameters,int type,CloseableHttpClient httpClient) {
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpPost request = null;
try {
request = new HttpPost(url);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
StringEntity entity = new StringEntity(parameters, "UTF-8");
if (type == Format_KeyValue) {
//logger.info("11111111");
// request.addHeader("Content-Type", "application/x-www-form-urlencoded");
entity.setContentType("application/x-www-form-urlencoded");
} else if (type == Format_Json) {
// request.addHeader("Content-Type", "application/json");
entity.setContentType("application/json");
} else {
logger.error("不支持的参数格式");
return null;
}
request.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
e.printStackTrace();
} finally {
if (request != null)
request.releaseConnection();
}
return null;
} */
}