java发送Http请求

java发送Http请求

发送get请求

private static String REMOTE_SERVER;
public static String sendGet(String path, Map<String, String> params) throws Exception {
        logger.info("sendGet path={}", path, params);
        //get
        String url = null;
        URIBuilder uriBuilder = new URIBuilder(REMOTE_SERVER);
        uriBuilder.setPath(path);
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        url = uriBuilder.build().toASCIIString();
        logger.info("url={}", url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        String response = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpget);
            HttpEntity httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity, "utf-8");
            EntityUtils.consume(httpEntity);
        } catch (IOException e) {
            logger.error("httputil sendGet error.", e);
            throw new DataCenterException(500, "httputil sendJsonPost error.");
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.error("httputil release httpClient error.", e);
                throw new DataCenterException(500, "httputil release httpClient error.");
            }
        }

        return response;
    }

发送Post请求

public static String sendPost(String path, Map<String, String> params) throws Exception {
        logger.info("sendPost path={}", path, params);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(REMOTE_SERVER);
        //post
        uriBuilder.setPath(path);
        String url = uriBuilder.build().toASCIIString();
        HttpPost httpPost = new HttpPost(url);

        String encode = "UTF-8";
        if (params.size() != 0) {
            List<NameValuePair> paramList = Lists.newArrayList();
            for (String key : params.keySet()) {
                paramList.add(new BasicNameValuePair(key, params.get(key)));
            }
            //模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, encode);
            httpPost.setEntity(entity);
        }

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        String response = null;

        try {
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                response = EntityUtils.toString(httpEntity, encode);
            }
            EntityUtils.consume(httpEntity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.error("release resouce error: " + e);
            }
        }
        return response;
    }

发送Json的Post请求

public static String sendJsonPost(String url, String json) throws Exception {
        logger.info("sendJsonPost url={}", url, json);
        URIBuilder uriBuilder = new URIBuilder(REMOTE_SERVER);
        uriBuilder.setPath(url);
        url = uriBuilder.build().toASCIIString();
        //post
        CloseableHttpClient httpClient = HttpClients.createDefault();
        System.out.println(url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        if (json != null){
            httpPost.setEntity(new StringEntity(json, "UTF-8"));
        }
        String responseContent = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            if (entity != null){
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }

        } catch (IOException e) {
            logger.error("httputil sendJsonPost error.", e);
            throw new DataCenterException(500, "httputil sendJsonPost error.");
        } finally {
            try {
                if (response != null) response.close();
            } catch (IOException e) {
                logger.error("httputil release response error.", e);
                throw new DataCenterException(500, "httputil release response error.");
            }
            try {
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                logger.error("httputil release httpClient error.", e);
                throw new DataCenterException(500, "httputil release httpClient error.");
            }
        }
        return responseContent;
    }

发送Json参数的Put请求

public static String sendJsonPut(String url, String json) throws Exception {
        logger.info("sendJsonPut url={}", url, json);
        URIBuilder uriBuilder = new URIBuilder(REMOTE_SERVER);
        uriBuilder.setPath(url);
        url = uriBuilder.build().toASCIIString();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        httpPut.addHeader("Content-Type", "application/json");
        httpPut.setEntity(new StringEntity(json, "UTF-8"));

        String responseContent = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPut);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            logger.error("httputil release response error.", e);
            throw new DataCenterException(500, "httputil sendJsonPost error.");
        } finally {
            try {
                if (response != null) response.close();
            } catch (IOException e) {
                logger.error("httputil release response error.", e);
                throw new DataCenterException(500, "httputil release response error.");
            }
            try {
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                logger.error("httputil release httpClient error.", e);
                throw new DataCenterException(500, "httputil release httpClient error.");
            }
        }
        return responseContent;
    }

发送Delete请求

public static String sendDelete(String path, Map<String, String> params) throws Exception {
        logger.info("sendDelete path={}", path, params);
        //get
        URIBuilder uriBuilder = new URIBuilder(REMOTE_SERVER);
        String url = null;
        uriBuilder.setPath(path);
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        url = uriBuilder.build().toASCIIString();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        String response = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity httpEntity = httpResponse.getEntity();

            if (httpEntity != null) {
                response = EntityUtils.toString(httpEntity, "utf-8");
            }

            EntityUtils.consume(httpEntity);
        } catch (IOException e) {
            logger.error("httputil sendGet error.", e);
            throw new DataCenterException(500, "httputil sendJsonPost error.");
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.error("httputil release httpClient error.", e);
                throw new DataCenterException(500, "httputil release httpClient error.");
            }
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值