HttpClient的HttpGet、HttpPost、HttpPut、HttpDelete工具类

//Http的get请求方法
public static String httpGet(String listenIp, String service, JSONObject jsonStr) {
        String saveProxyUrl = "http://" + listenIp +":8080" + service;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String result = null;

        try {
            Set<String> keySet = jsonStr.keySet();
            Iterator<String> it = keySet.iterator();
            /*
             * 由于GET请求的参数都是拼装在URL地址后方,所以我们要构建一个URL,带参数
             */
            URIBuilder uriBuilder = new URIBuilder(saveProxyUrl);
            List<NameValuePair> list = new LinkedList<>();

            while(it.hasNext()){
                String key = it.next();
                BasicNameValuePair param = new BasicNameValuePair(key, jsonStr.getString(key));
                list.add(param);
            }
            uriBuilder.setParameters(list);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();

            HttpRequestBase saveProxy = new HttpGet(uriBuilder.build());
            saveProxy.setHeader("Accept", "*/*");
            saveProxy.setHeader("Cache-Control", "no-cache");
            saveProxy.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
            saveProxy.setConfig(requestConfig);

            client = HttpClients.createDefault();
            response = client.execute(saveProxy);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            LoggerUtil.debug("========== " + res);

            JSONObject jsonObject = JSON.parseObject(res);
            result = jsonObject.getString("result");
            JSONObject jsonObject1 = JSONObject.parseObject(result);
            if (!Constants.HTTP_SUCCESS.equalsIgnoreCase(jsonObject.getString("code"))){
                throw new Exception("get httpGet happened exception, detail:{}");
            }
        } catch (Exception e) {
            LoggerUtil.debug("get proxy happened exception, detail:{}", Utils.getStackTrace(e));
            throw new ServiceException(RetCode.INNER_ERROR, e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {

                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (Exception e) {

                }
            }
        }

        return result;
    }
//HttpPost的请求方法
public static String httpPost(String listenIp, String service, String jsonStr) {
        String saveProxyUrl = "http://" + listenIp +":8080" + service;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String result = null;

        try {
            ObjectMapper proxyMapper = new ObjectMapper();
            Map<String,Object> proxyData = proxyMapper.readValue(jsonStr, Map.class);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();

            HttpPost saveProxy = new HttpPost(saveProxyUrl);
            saveProxy.setHeader("Accept", "*/*");
            saveProxy.setHeader("Cache-Control", "no-cache");
            saveProxy.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
            saveProxy.setEntity(new StringEntity(proxyMapper.writeValueAsString(proxyData), ContentType.create("application/json", "UTF-8")));
            saveProxy.setConfig(requestConfig);

            client = HttpClients.createDefault();
            response = client.execute(saveProxy);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            LoggerUtil.debug("========== " + res);

            JSONObject jsonObject = JSON.parseObject(res);
            result = jsonObject.getString("code");
        } catch (Exception e) {
            LoggerUtil.debug("save proxy happened exception, detail:{}", Utils.getStackTrace(e));
            throw new ServiceException(RetCode.INNER_ERROR, e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {

                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (Exception e) {

                }
            }
        }

        return result;
    }
 /HttpPut更新的时候用这个
    public static String HttpPut(String listenIp, String service, String jsonStr) {
        String saveProxyUrl = "http://" + listenIp +":8080" + service;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String result = null;

        try {
            ObjectMapper proxyMapper = new ObjectMapper();
            Map<String,Object> proxyData = proxyMapper.readValue(jsonStr, Map.class);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();

            HttpPut saveProxy = new HttpPut(saveProxyUrl);
            saveProxy.setHeader("Accept", "*/*");
            saveProxy.setHeader("Cache-Control", "no-cache");
            saveProxy.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
            saveProxy.setEntity(new StringEntity(proxyMapper.writeValueAsString(proxyData), ContentType.create("application/json", "UTF-8")));
            saveProxy.setConfig(requestConfig);

            client = HttpClients.createDefault();
            response = client.execute(saveProxy);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            LoggerUtil.debug("========== " + res);

            JSONObject jsonObject = JSON.parseObject(res);
            result = jsonObject.getString("code");
        } catch (Exception e) {
            LoggerUtil.debug("save proxy happened exception, detail:{}", Utils.getStackTrace(e));
            throw new ServiceException(RetCode.INNER_ERROR, e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {

                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (Exception e) {

                }
            }
        }

        return result;
    }
   //HttpDelete请求方法:删除的时候用这个
    public static String httpDelete(String listenIp, String service, String jsonStr) {
        String saveProxyUrl = "http://" + listenIp +":8080" + service + "?/id=3" ;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String result = null;

        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();

            HttpDeleteWithBody saveProxy = new HttpDeleteWithBody(saveProxyUrl);
            saveProxy.setHeader("Accept", "*/*");
            saveProxy.setHeader("Cache-Control", "no-cache");
            saveProxy.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
            saveProxy.setEntity(new StringEntity(jsonStr, ContentType.create("application/json", "UTF-8")));
            saveProxy.setConfig(requestConfig);

            client = HttpClients.createDefault();
            response = client.execute(saveProxy);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            LoggerUtil.debug("========== " + res);

            JSONObject jsonObject = JSON.parseObject(res);
            result = jsonObject.getString("result");
        } catch (Exception e) {
            LoggerUtil.debug("save proxy happened exception, detail:{}", Utils.getStackTrace(e));
            throw new ServiceException(RetCode.INNER_ERROR, e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {

                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (Exception e) {

                }
            }
        }

        return result;
    }
    //传入body,需要重写class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
    private static final String METHOD_NAME = "DELETE";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri) {
        super();
        setURI(uri);
    }

    public HttpDeleteWithBody() {
        super();
    }
}
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
    private static final String METHOD_NAME = "DELETE";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri) {
        super();
        setURI(uri);
    }

    public HttpDeleteWithBody() {
        super();
    }
}
发布了77 篇原创文章 · 获赞 39 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_33824312/article/details/93750769