标签:web开发 httpclient4.3.x httpcomponents
在web开发中,我们经常需要模拟post及get请求,现在网上比较多的是使用httpclient3.x,然而httpclient4.x已经发布好几年了,而且4.x之后改名为HttpComponents,显然是今后的趋势.public 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(50) .setConnectTimeout(50) .setSocketTimeout(50).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(); }
public void requestPost(String url,List<NameValuePair> params) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = httpclient.execute(httppost); System.out.println(response.toString()); HttpEntity entity = response.getEntity(); String jsonStr = EntityUtils.toString(entity, "utf-8"); System.out.println(jsonStr); httppost.releaseConnection(); }
public static void main(String[] args){ try { String loginUrl = "http://localhost:8080/yours"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", "zhang")); params.add(new BasicNameValuePair("passwd", "123")); requestPost(loginUrl,params); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
httpclient4.3.x模拟post及get请求,布布扣,bubuko.com
标签:web开发 httpclient4.3.x httpcomponents
原文地址:http://blog.csdn.net/gaolu/article/details/38228513