HttpClient学习

这篇博客详细介绍了HttpClient的使用,从引入jar包、发送无参数GET请求,到处理带参数的情况、设置代理、超时以及POST请求,特别强调了HttpClient在处理URL编码和发送json格式POST请求时的注意事项。
摘要由CSDN通过智能技术生成

HttpClient学习

背景

昨天快要下班的时候,被同事留下帮忙一起看HttpClient的问题,当时是一个json类型的请求使用的表单的请求方式,
导致请求报错。虽然说后面问题被解决了,但是还是觉得基础不够扎实,所以需要补充一下,已备查用。

测试原生的API

引入jar包

<dependencies>
         <dependency>
             <groupId>org.apache.httpcomponents</groupId>
             <artifactId>httpclient</artifactId>
             <version>4.5.13</version>
         </dependency>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.13</version>
             <scope>compile</scope>
         </dependency>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.12</version>
             <scope>test</scope>
         </dependency>
     </dependencies>

使用原生URL调用查询bing首页

代码
    @Test
    public void testOriginalUrl() throws Exception {
        String bingUrl = "https://cn.bing.com/";
        URL url = new URL(bingUrl);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        try(
                InputStream is = httpURLConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
            ) {
            String line;
            while((line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
结果

                
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值