apache http get 和 post 请求

1、首先要把jar依赖进项目

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.3</version>
</dependency>

2、get/post方法

/**
     * http post 请求
     * 1、创建 client 实例
     * 2、创建 post 实例
     * 3、设置 post 参数
     * 4、发送请求
     */
    public static String post(String url, Map<String, String> params) {
        if (url == null) {
            LOGGER.info("http url can not be empty!");
        }
        String respCtn = "";
        // 1、创建 client 实例
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 2、创建 post 实例
        HttpPost post = new HttpPost(url);
        
        ArrayList<NameValuePair> reqParams = null;
        if (params != null && !params.isEmpty()) {
            reqParams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> e : params.entrySet()) {
                reqParams.add(new BasicNameValuePair(e.getKey(), e.getValue()));
            }
        }

        HttpResponse response = null;
        try {
            if (reqParams != null)
                // 3、设置 post 参数
                post.setEntity(new UrlEncodedFormEntity(reqParams, "UTF-8"));
            // 4、发送请求
            response = httpclient.execute(post);
            respCtn = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            LOGGER.error("Fail to connect to remote host [" + url + "]" + e);
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                }
            }
        }
        return respCtn;
    }

/**
     * http get 请求
     * 
     * @param String
     *            url
     * 
     */
    public static String doGet(String url) {
        if (url == null || url.isEmpty()) {
            LOGGER.info("http url can not be empty!");
        }
        String respCtn = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpResponse response = null;
            HttpGet get = new HttpGet(url);
            response = httpclient.execute(get);
            respCtn = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                }
            }
        }
        return respCtn;
    }

 

转载于:https://www.cnblogs.com/dannyyao/p/6972702.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值