httpclient

添加架包支持:

1
2
3
4
5
  <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
</dependency>

  

第一步是获取http客户端的实列,编写代码

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.java.httpclient;
 
import java.io.IOException;
 
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
public class Helloword {
    public static void main(String[] args) {
        CloseableHttpClient  httpclient=HttpClients.createDefault(); //创建浏览器实列
        HttpGet httpget=new HttpGet("http://www.java1234.com"); //创建get实列
        CloseableHttpResponse response=null;
        try {
            //执行get请求
            response=httpclient.execute(httpget);
        } catch (ClientProtocolException e) { //http协议异常
            e.printStackTrace();
        } catch (IOException e) { //io异常
            e.printStackTrace();
        }
         
        //返回实体
         HttpEntity entity=response.getEntity();
         try {
            System.out.println("输出实体:"+EntityUtils.toString(entity,"utf-8"));
        } catch (ParseException e) { //解析异常
            e.printStackTrace();
             
        } catch (IOException e) {  //io 异常
 
            e.printStackTrace();
        }
        try {
            response.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
    }
}

 

  

 

posted on   nidegui  阅读(210)  评论(1编辑  收藏  举报
努力加载评论中...

点击右上角即可分享
微信分享提示