httpclient 4.0 使用
httclient 正常流程
1、创建httpclient实例
HttpClient httpClient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.createDefault();
2、创建请求实例
HttpGet httpGet = new HttpGet(url); HttpPost httpPost = new HttpPost(url);
3、补充头信息(可选)
httpPost.addHeader("Referer", "http://iservice.10010.com/e4/query/basic/history_list.html");
httpPost.addHeader(" Cookie ", " td_cookie=18446744072103645798; mallcity=31|310; ");
4、补充请求实体
1)url是restful风格,已经包含需要传入的参数。可以跳过直接到下一步操作。
url="https://ssoqa.99bill.com/sso/login/smsvalidate.htm?method=loginErrorCount&idContent=1234567"
2)表单
List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("querytype", "0001")); nvps.add(new BasicNameValuePair("querycode", "0001")); nvps.add(new BasicNameValuePair("billdate", "201608")); nvps.add(new BasicNameValuePair("flag", "2")); httpPost.setEntity(new UrlEncodedFormEntity(nvps));
5、请求执行
HttpResponse response = httpClient.execute(httpGet); CloseableHttpResponse response = httpclient.execute(httpGet); byte[] response = httpClient.execute(httpGet,handler);
6、读取响应内容
if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful } finally { instream.close(); } } }
7、释放连接
response.close();
需要引用的jar
<!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.4</version> </dependency> <!-- httpclient -->
posted on 2017-02-14 23:22 applelongmoon 阅读(1555) 评论(0) 编辑 收藏 举报