HttpClient详细使用示例

HttpClient

    博客地址:https://blog.csdn.net/justry_deng/article/details/81042379

HttpClientUtil封装的工具类

   github:https://github.com/Arronlong/httpclientutil

HttpClient作者封装的工具类

  GET无参工具类

package com.xiaomin.wechat.util;

import org.apache.http.HttpEntity;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author 晓敏
 * @create 2019-11-15 10:22
 */
public class HttpGetUtil {

    /**
     * GET无参工具类
     * @param url 接口地址
     * @return 调用接口后返回的结果
     */
    public static String doGet(String url){
        String result="";
        CloseableHttpResponse response=null;
        // 1、获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        ///2、创建Get请求
        HttpGet httpGet = new HttpGet(url);
        try {
            // 3、由客户端执行(发送)Get请求
             response = httpClient.execute(httpGet);
            ///4、从响应模型中获取响应实体
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");//响应的内容进行编码
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(httpClient!=null){//关闭连接
                    httpClient.close();
                }
                if(response!=null){//关闭
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

测试结果:

@Test
    public void fun2(){
        String result = HttpGetUtil.doGet("http://localhost:8081/getfirst");
        System.out.println(result);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值