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

httpclient 4.0 使用

时间:2017-02-15 00:29:13      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:apach   query   下一步   释放   pair   pen   puts   风格   nbsp   

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 -->

 

httpclient 4.0 使用

标签:apach   query   下一步   释放   pair   pen   puts   风格   nbsp   

原文地址:http://www.cnblogs.com/applemoon/p/6399653.html

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