标签:
public static String doPost(String url, String encoding, String contentType, String sendData)
throws Exception {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient httpclient = httpClientBuilder.build();
HttpPost httppost = new HttpPost(url);
StringEntity myEntity = new StringEntity(sendData, encoding);
myEntity.setContentType(contentType);
httppost.setEntity(myEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(resEntity.getContent(), encoding);
char[] buff = new char[‘?‘];
StringBuilder sb = new StringBuilder();
int length;
while ((length = reader.read(buff)) != -1) {
sb.append(new String(buff, 0, length));
}
httpclient.close();
return sb.toString();
}
public static void requestGet(String urlWithParams) throws Exception {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
// HttpGet httpget = new HttpGet("http://www.baidu.com/");
HttpGet httpget = new HttpGet(urlWithParams);
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
.setSocketTimeout(5000).build();
httpget.setConfig(requestConfig);
CloseableHttpResponse response = httpclient.execute(httpget);
System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(entity);// , "utf-8");
System.out.println(jsonStr);
httpget.releaseConnection();
}
标签:
原文地址:http://www.cnblogs.com/fanguangdexiaoyuer/p/5796710.html