码迷,mamicode.com
首页 > Web开发 > 详细

httpClient 4.x post get方法

时间:2016-08-22 20:01:27      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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();

}

httpClient 4.x post get方法

标签:

原文地址:http://www.cnblogs.com/fanguangdexiaoyuer/p/5796710.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!