方式一:commons-httpclient-3.1.jar
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
private String requestTwo(String url,Map<String,String> map) throws Exception{
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");
try {
String str = JSONObject.fromObject(map).toString();
RequestEntity entity = new StringRequestEntity(str, "application/json", "UTF-8");
postMethod.setRequestEntity(entity);
httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
方式二:httpclient-4.5.2.jar
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
private String requestTwo(String url,Map<String,String> map) throws Exception{
/** 请求上游 **/
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json;");
String str = JSONObject.fromObject(map).toString();
StringEntity entity = new StringEntity(URLEncoder.encode(str,"UTF8"));
post.setEntity(entity);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(50);
HttpClient ht = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpResponse response = ht.execute(post);
/** 返回结果处理 **/
String resp = new String();
if (response != null) {
resp = EntityUtils.toString(response.getEntity());
}
return resp;
}
以上两种方式是通过不同jar包实现访问,使用前请先确认是否有对应jar文件。