httpClient实例
基于httpclient4.3.6写的测试客户端,使用PoolingHttpClientConnectionManager保证线程安全
public class TestHttpClient { /** * */ @Test public void testGet() throws IOException { System.out.println("开始测试"); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(100); CloseableHttpClient httpclient = HttpClients.custom() .setConnectionManager(cm) .build(); try { HttpGet httpget = new HttpGet("http://localhost:8089/httpservice/httpService/testGet"); CloseableHttpResponse response = httpclient.execute(httpget); try { InputStream is = response.getEntity().getContent(); String result = getStreamAsString(is, "UTF-8"); System.out.println(result); } finally { response.close(); httpget.releaseConnection(); } HttpPost httpPost = new HttpPost("http://localhost:8089/httpservice/httpService/testPost"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); httpPost.releaseConnection(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.close(); }; } private String getStreamAsString(InputStream is, String s) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, s), 8192); StringWriter writer = new StringWriter(); char[] chars = new char[8192]; int count = 0; while ((count = reader.read(chars)) > 0) { writer.write(chars, 0, count); } return writer.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) is.close(); } return ""; } }
相关推荐
84487600 2020-08-16
标题无所谓 2020-06-14
yanghui0 2020-06-09
似水流年梦 2020-08-09
knightwatch 2020-07-26
fengchao000 2020-06-16
sicceer 2020-06-12
yanghui0 2020-06-09
创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。
wanghongsha 2020-06-04
jiaguoquan00 2020-05-26
zhaolisha 2020-05-16
wanghongsha 2020-05-05
wanghongsha 2020-04-14
knightwatch 2020-04-11
hygbuaa 2020-03-27
zergxixi 2020-03-24