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

 

转载于:https://www.cnblogs.com/applemoon/p/6399653.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值