HttpClient发送Get和Post请求

今天带来一个基于HttpClient发送Get以及Post请求,代码一律经过测试,可以放心直接使用。
注意: ResponseBase:自定义统一返回格式,CustomException:自定义异常,以上两个都不需要关心。

  • 1:在pom中加入相关依赖
        <!-- httpclient相关 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.7</version>
        </dependency>
  • 2:发送get请求
/**
     * 发送get请求
     *
     * @param url 请求地址
     * @return 同一类型
     * @throws IOException 异常
     */
    public ResponseBase doGet(String url) {
        try{
            System.out.println("地址url:" + url);
            //创建一个httpGet请求
            HttpGet request = new HttpGet(url);
            //创建一个htt客户端
            HttpClient httpClient = HttpClientBuilder.create().build();
            //添加cookie到头文件
//        request.addHeader("Cookie", cookie);
            //接受客户端发回的响应
            HttpResponse httpResponse = httpClient.execute(request);
            //获取返回状态
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            //如果是响应成功
            if (statusCode != HttpStatus.SC_OK) {
                 //这是自定义的异常 可以不用关心
                throw new CustomException(setResultError("发送GET请求失败"));
            }
            //得到客户段响应的实体内容
            HttpEntity responseHttpEntity = httpResponse.getEntity();
            String string = EntityUtils.toString(responseHttpEntity, "utf-8");
            System.out.println("发送GET请求成功:" + string);
            return setResultSuccessData(string, "发送GET请求成功");
        }catch (Exception e){
            throw new CustomException(setResultError("发送GET请求异常:"+e.getMessage()));
        }
    }
  • 3:发送post请求
/**
     * post请求
     *
     * @param url   请求地址
     * @param jsonParam 参数集合
     * @throws IOException 异常
     */
    public ResponseBase doPost(String url, String jsonParam) {
        try{
            System.out.println("地址url:" + url);
            System.out.println("参数param:" + jsonParam.toString());
            // 获取默认的请求客户端
            HttpClient httpClient = HttpClientBuilder.create().build();
            // 通过HttpPost来发送post请求
            HttpPost httpPost = new HttpPost(url);
            //设置参数  这是第一种传递参数的方法 比较麻烦 但是比较灵活 但是测试没通过 慎用
//            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(param);
            //格式
//            formEntity.setContentType("application/json");
            //字符串类型
//            formEntity.setContentEncoding("utf-8");
            StringEntity stringEntity = new StringEntity(jsonParam);
            stringEntity.setContentEncoding("utf-8");
            stringEntity.setContentType("application/json");
            // 第一步:通过setEntity 将我们的entity对象传递过去
            httpPost.setEntity(stringEntity);
            // 通过client来执行请求,获取一个响应结果
            HttpResponse execute = httpClient.execute(httpPost);
            int statusCode = execute.getStatusLine().getStatusCode();
            //失败
            if (statusCode != HttpStatus.SC_OK) {
                throw new CustomException(setResultError("发送POST请求失败"+execute.getEntity()));
            }
            HttpEntity entity = execute.getEntity();
            String str = EntityUtils.toString(entity, "utf-8");
            System.out.println(str);
            return setResultSuccessData(str, "发送POST请求成功");
        }catch (Exception e){
            throw new CustomException(setResultError("发送POST请求异常:"+e.getMessage()));
        }
    }

这样我们发送请求的核心代码就已经完成了,非常的简单,也是为了给自己做个笔记,也希望能帮到大家。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值