Http Client 的使用

精选30+云产品,助力企业轻松上云!>>> hot3.png

  1. 介绍

            HttpClient是Apache公司的产品,是Http Components下的一个子组件

     2. 特点

            1. 基于标准、纯净的java语言。实现了Http1.0、Http1.1。

            2. 可以扩展的面向对象的结构实现了http的全部方法(get,post,put,delete,head,options,andtrace)

            3.支持Https协议。

            4.通过http代理建议透明的连接。

            5. 自动处理Set-cookie中的cookie。

     3.使用 -- 创建httpClient客户端

public class HttpTests{
    CloseableHttpClient httpClient;
    
    @Before
    public void init(){
         // 创建httpClient的客户端
         httpClient = HttpClients.createDefault();
    }

}

         3.1 发起get请求

@Test
public void testGet() throws IOException{
    // 发起什么请求就new什么, 比如new HttpPost 等等....
    HttpGet request= new HttpGet('http://www.baidu.com');
    // 执行请求
    String response = this.httpClient.execute(request,new BasicResponseHandler());
    system.out.println(response);

}

        3.2 发起post请求

@Test
public void testPost() throws IOException{
    // 发起什么请求就new什么, 比如new HttpPost 等等....
    HttpPost request= new HttpPost('https://my.oschina.net');
    // 设置请求头,欺骗一下开源中国。因为开源中国限制爬虫访问
    request.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
    // 执行请求
    String response = this.httpClient.execute(request,new BasicResponseHandler());
    system.out.println(response);
}

        3.3 使用Get请求访问自己的服务器,实现远程调用

@Test
public void testGetPojo() throws IOException{
    // 发起请求  // http://localhost:8080/hello 服务器地址
    HttpGet request= new HttpGet('http://localhost:8080/hello');
    // 执行请求,获得json数据
    String response = this.httpClient.execute(request,new BasicResponseHandler());
    // json数据转为对象数据便可, 可使用ObjectMapper
    system.out.println(response);

}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值