Skip to content

Instantly share code, notes, and snippets.

@qlong8807
Last active August 2, 2019 08:09
Show Gist options
  • Save qlong8807/b5b55956bd937764bf25f2e8b2d2aa6b to your computer and use it in GitHub Desktop.
Save qlong8807/b5b55956bd937764bf25f2e8b2d2aa6b to your computer and use it in GitHub Desktop.
Content-Type不同,写法也不同
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.*;
public class HttpClient{
/**
* 发送application/json的post请求
* @param url 支持https
* @param headers
* @param params
* @param charset UTF-8
* @return
* @throws UnsupportedEncodingException
*/
public static String post(String url, Map<String, String> headers, Map<String, String> params,String charset) throws UnsupportedEncodingException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
HttpPost httpPost = new HttpPost(url);
if (null != headers && headers.size() > 0) {
for(String key : headers.keySet())
httpPost.addHeader(key,headers.get(key));
}
if (null != params && params.size() > 0) {
JSONObject jsonParam = new JSONObject();
for (String key : params.keySet()) {
jsonParam.put(key, params.get(key));
}
StringEntity entity = new StringEntity(jsonParam.toString(), charset);
entity.setContentEncoding(charset);
entity.setContentType("application/json;charset=utf-8");
RequestConfig config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
httpPost.setConfig(config);
httpPost.setEntity(entity);
}
return executeRequest(httpPost, charset);
}
/**
* 发送/x-www-form-urlencoded或者form-data的post请求
* @param url 支持https
* @param headers
* @param params
* @param charset UTF-8
* @return
* @throws UnsupportedEncodingException
*/
public static String post2(String url, Map<String, String> headers, Map<String, String> params,String charset) throws UnsupportedEncodingException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("connection", "Keep-Alive");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
if (null != headers && headers.size() > 0) {
for(String key : headers.keySet())
httpPost.addHeader(key,headers.get(key));
}
if (null != params && params.size() > 0) {
List<NameValuePair> nvps = new ArrayList<>();
for (String key : params.keySet()) {
nvps.add(new BasicNameValuePair(key,params.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, charset);
formEntity.setContentEncoding(charset);
RequestConfig config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
httpPost.setConfig(config);
httpPost.setEntity(formEntity);
}
return executeRequest(httpPost, charset);
}
/**
* 执行一个http请求,传递HttpGet或HttpPost参数
*/
public static String executeRequest(HttpUriRequest httpRequest, String charset) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
CloseableHttpClient httpclient;
if ("https".equals(httpRequest.getURI().getScheme())){
httpclient = createSSLInsecureClient();
}else{
httpclient = HttpClients.createDefault();
}
String result = "";
try {
try {
CloseableHttpResponse response = httpclient.execute(httpRequest);
HttpEntity entity = null;
try {
entity = response.getEntity();
result = EntityUtils.toString(entity, charset);
} finally {
EntityUtils.consume(entity);
response.close();
}
} finally {
httpclient.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
return result;
}
/**
* 创建 SSL连接
*/
public static CloseableHttpClient createSSLInsecureClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
}
@qlong8807
Copy link
Author

以上使用的是HttpClient 4.5.3,4.5以下版本设置超时方法与此不同。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment