HttpClient 自己整合的发送get post put 和delete 一个方法

啥也不说,直接上代码。

/**
     *
     * @param postType 0:get,1:post, 2:put, 3:delete
     * @param url
     * @param contentType {@link org.apache.http.entity.ContentType contentType}
     * @param headers 请求头参数集合
     * @param clientCookies 包含的cookie
     * @param jsonObject 请求参数
     * @return
     */
    public static CloseableHttpResponse httpClient(String postType, String url, ContentType contentType, Map<String,String> headers,
        List<BasicClientCookie> clientCookies, JSONObject jsonObject) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        if(clientCookies != null && !clientCookies.isEmpty()) {
            BasicCookieStore cookieStore = new BasicCookieStore();
            cookieStore.addCookies(clientCookies.toArray(new Cookie[]{}));
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        }

        CloseableHttpResponse httpResponse = null;
        HttpEntity entity = null;
        try {
            if ("0".equals(postType)) {
                //===== get =====//
                URIBuilder uriBuilder = new URIBuilder(url);
                // 设置参数
                if(jsonObject != null && !jsonObject.isEmpty()) {
                    List<NameValuePair> list = new LinkedList<>();
                    for (Map.Entry<String,?> entry : jsonObject.entrySet()) {
                        list.add(new BasicNameValuePair(entry.getKey(), jsonObject.getString(entry.getKey())));
                    }
                    uriBuilder.addParameters(list);
                }

                HttpGet httpGet = new HttpGet(uriBuilder.build());
                httpGet.setProtocolVersion(HttpVersion.HTTP_1_0);
                //设置header
                setHttpClientHeaders(contentType, headers, httpGet);
                //发送请求
                httpResponse = httpClient.execute(httpGet);
            } else if("1".equals(postType)) {
                //===== post =====//
                HttpPost httpPost = new HttpPost(url);
                // 设置请求头
                setHttpClientHeaders(contentType, headers, httpPost);
                //增加参数
                if(contentType == ContentType.APPLICATION_JSON) {
                    if(jsonObject != null && !jsonObject.isEmpty()) {
                        httpPost.setEntity(new StringEntity(jsonObject.toString(),"UTF-8"));
                    }
                } else if(contentType == ContentType.APPLICATION_FORM_URLENCODED) {
                    // 设置参数
                    setHttpClientEntity(jsonObject, httpPost);
                }

                httpResponse = httpClient.execute(httpPost);
            } else if("2".equals(postType)) {
                //===== put =====//
                HttpPut httpPut = new HttpPut(url);
                // 设置请求头
                setHttpClientHeaders(contentType, headers, httpPut);
                // 设置参数
                setHttpClientEntity(jsonObject, httpPut);

                httpResponse = httpClient.execute(httpPut);
            } else if ("3".equals(postType)) {
                //===== delete =====//
                // HttpDelete httpDelete = new HttpDelete(url);
                HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
                // 设置请求头
                setHttpClientHeaders(contentType, headers, httpDelete);
                // 设置参数
                setHttpClientEntity(jsonObject, httpDelete);

                httpResponse = httpClient.execute(httpDelete);
            }
            // //返回结果
            // entity = httpResponse.getEntity();
            // String s = EntityUtils.toString(entity, "utf-8");
            // EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return httpResponse;
    }

    /**
     * 根据响应获取响应实体
     *
     * @param response
     * @return
     */
    public static <T> T getContent(CloseableHttpResponse response, Class<T> clazz) {
        HttpEntity entity = response.getEntity();// 获取响应实体
        T content = null;
        try {
            if(content instanceof String) {
                content = (T) EntityUtils.toString(entity, "utf-8");// 用string接收响应实体
            } else if(clazz.isArray()) {
                
                content = (T) EntityUtils.toByteArray(entity);
            }
            EntityUtils.consume(entity);// 消耗响应实体,并关闭相关资源占用
        } catch (ParseException e1) {
            e1.fillInStackTrace();
        } catch (Exception e1) {
            e1.fillInStackTrace();
        } finally {
            release(response);
        }
        return content;
    }

    public static void release(CloseableHttpResponse response) {
        if(response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void setHttpClientHeaders(ContentType contentType, Map<String, String> headers, HttpRequestBase httpClient) {
        httpClient.setHeader("Content-type", contentType.getMimeType());
        httpClient.setHeader("DataEncoding", "UTF-8");
        if(headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpClient.setHeader(entry.getKey(),entry.getValue());
            }
        }
    }

    private static void setHttpClientEntity(JSONObject jsonObject, HttpEntityEnclosingRequestBase httpClient) throws UnsupportedEncodingException {
        if(jsonObject != null && !jsonObject.isEmpty()) {
            List<NameValuePair> list = new LinkedList<>();
            for (Map.Entry<String,?> entry : jsonObject.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), jsonObject.getString(entry.getKey())));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
            httpClient.setEntity(formEntity);
        }
    }

    @NotThreadSafe
    static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
        public 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(); }
    }

    public static void main(String[] args) throws IOException {

        String jsessionId = RandomStringUtils.randomAlphanumeric(32).toUpperCase();
        String ocrCode = getOCRCode("http://localhost:8888/crm/res/Kaptcha.jpg", jsessionId);
        // loginCRM("http://localhost:8888/crm/login_checkUser.json","superadmin","29AD0E3FD3DB681FB9F8091C756313F7","99999999",ocrCode,jsessionId);
    }

  同一个方法根据传入参数可以执行get post put 和 delete 方法

posted @ 2019-12-18 20:09  margo  阅读(212)  评论(0编辑  收藏  举报