java使用httpclient发送http请求

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,将httpclient封装成一个工具类,方便直接调用
环境:jdk1.8+maven

1.引入maven依赖

		<!-- 引入httpclient依赖-->
		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <!--将数据实体为json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

2.编写工具类

public class HttpRequestUtils {

    private static void httpRespond(HttpUriRequest httpRequest,HttpRespCallBack httpRespCallBack) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpRequest);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                httpRespCallBack.resp(response);
            }else {
                throw new RuntimeException("响应内容为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送get请求
     * @param url 请求地址
     * @param httpRespCallBack 响应内容
     */
    public static void sendHttGet(String url,HttpRespCallBack httpRespCallBack){
        HttpGet get=new HttpGet(url);
        httpRespond(get,httpRespCallBack);
    }

    /**
     *发送post请求
     * @param url 请求地址
     * @param params 请求参数
     * @param httpRespCallBack 请求回调
     */
    public static void sendHttpPost(String url, Map<String,Object> params,HttpRespCallBack httpRespCallBack){
        HttpPost post=new HttpPost(url);
        HttpEntity httpEntity=new StringEntity(JSONObject.toJSONString(params),"utf-8");
        post.setEntity(httpEntity);
        post.setHeader("Content-Type", "application/json;charset=utf8");
        httpRespond(post,httpRespCallBack);
    }

    /**
     * put请求
     * @param url 请求地址
     * @param params 请求参数
     * @param httpRespCallBack 请求回调
     */
    public static void sendHttpPut(String url,Map<String,Object> params,HttpRespCallBack httpRespCallBack){
        HttpPut httpPut=new HttpPut(url);
        HttpEntity httpEntity=new StringEntity(JSONObject.toJSONString(params),"utf-8");
        httpPut.setEntity(httpEntity);
        httpPut.setHeader("Content-Type", "application/json;charset=utf8");
        httpRespond(httpPut,httpRespCallBack);
    }

    /**
     * delete请求
     * @param url 请求地址
     * @param httpRespCallBack 请求回调
     */
    public static void sendHttpDelete(String url,HttpRespCallBack httpRespCallBack){
        HttpDelete httpDelete=new HttpDelete(url);
        httpRespond(httpDelete,httpRespCallBack);
    }

3.请求响应接口

@FunctionalInterface
public interface HttpRespCallBack {
    void resp(HttpResponse httpResponse) ;
}

4.请求测试

 /**
     * get请求
     */
    public static void doGetTest() {

        HttpRequestUtils.sendHttGet("http://localhost:8081/pcp/basic/dict/findAll",(response)->{
            try {
                System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


    /**
     * post请求
     *
     * @date 2018年7月13日 下午4:18:50
     */
    public static void doPostTest() {
        Map<String,Object> map=new HashMap<>();
        map.put("locationCode","ABCDEFGH");
        HttpRequestUtils.sendHttpPost("http://localhost:8081/pcp/basic/location/add",map,
                (resp)->{
                    try {
                        System.out.println(EntityUtils.toString(resp.getEntity()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }

    //delete请求
    public static void doDeleteTest() {
        HttpRequestUtils.sendHttpDelete("http://localhost:8081/pcp/basic/location/delete?id=1", (response) -> {
            try {
                System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值