Java - HttpClient

陈高寒
2023-12-01

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net 

package chimomo.learning.java.code.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Chimomo
 */
public class HttpClient {

    /**
     * Get.
     *
     * @param url     The request url
     * @param headers The request headers
     * @return The response string
     */
    public static String get(String url, Map<String, String> headers) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpGet httpGet;
        String response;
        BasicCookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookies(Cookie.get());

        try {
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpGet = new HttpGet(url);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }

            httpResponse = httpClient.execute(httpGet);

            // Get response.
            HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity, "UTF-8");

            // Get cookies.
            List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
            } else {
                org.apache.http.cookie.Cookie[] cookiesArr = new org.apache.http.cookie.Cookie[cookies.size()];
                for (int i = 0; i < cookies.size(); i++) {
                    cookiesArr[i] = cookies.get(i);
                }
                Cookie.set(cookiesArr);
            }
        } catch (Exception ex) {
            response = null;
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception ex) {
            }
        }

        return response;
    }

    /**
     * Post.
     *
     * @param url     The request url
     * @param headers The request headers
     * @param body    The request body
     * @return The response string
     */
    public static String post(String url, Map<String, String> headers, String body) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpPost httpPost;
        String response;
        BasicCookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookies(Cookie.get());

        try {
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpPost = new HttpPost(url);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }

            // Update StringEntity to use charset.
            StringEntity se = new StringEntity(body, "utf-8");
            httpPost.setEntity(se);

            httpResponse = httpClient.execute(httpPost);

            // Get response.
            HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity, "UTF-8");

            // Get cookies.
            List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
            } else {
                org.apache.http.cookie.Cookie[] cookiesArr = new org.apache.http.cookie.Cookie[cookies.size()];
                for (int i = 0; i < cookies.size(); i++) {
                    cookiesArr[i] = cookies.get(i);
                }
                Cookie.set(cookiesArr);
            }
        } catch (Exception ex) {
            response = null;
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception ex) {
            }
        }

        return response;
    }

    /**
     * Delete.
     *
     * @param url     The request url
     * @param headers The request headers
     * @return The response string
     */
    public static String delete(String url, Map<String, String> headers) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpDelete httpDelete;
        String response;
        BasicCookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookies(Cookie.get());

        try {
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpDelete = new HttpDelete(url);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpDelete.addHeader(entry.getKey(), entry.getValue());
            }

            httpResponse = httpClient.execute(httpDelete);

            // Get response.
            HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity, "UTF-8");

            // Get cookies.
            List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
            } else {
                org.apache.http.cookie.Cookie[] cookiesArr = new org.apache.http.cookie.Cookie[cookies.size()];
                for (int i = 0; i < cookies.size(); i++) {
                    cookiesArr[i] = cookies.get(i);
                }
                Cookie.set(cookiesArr);
            }
        } catch (Exception ex) {
            response = null;
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception ex) {
            }
        }

        return response;
    }

    /**
     * Put.
     *
     * @param url     The request url
     * @param headers The request headers
     * @param body    The request body
     * @return The response string
     */
    public static String put(String url, Map<String, String> headers, String body) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpPut httpPut;
        String response;
        BasicCookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookies(Cookie.get());

        try {
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpPut = new HttpPut(url);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPut.addHeader(entry.getKey(), entry.getValue());
            }

            // Update StringEntity to use charset.
            StringEntity se = new StringEntity(body, "utf-8");
            httpPut.setEntity(se);

            httpResponse = httpClient.execute(httpPut);

            // Get response.
            HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity, "UTF-8");

            // Get cookies.
            List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
            } else {
                org.apache.http.cookie.Cookie[] cookiesArr = new org.apache.http.cookie.Cookie[cookies.size()];
                for (int i = 0; i < cookies.size(); i++) {
                    cookiesArr[i] = cookies.get(i);
                }
                Cookie.set(cookiesArr);
            }
        } catch (Exception ex) {
            response = null;
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception ex) {
            }
        }

        return response;
    }

    /**
     * Patch.
     *
     * @param url     The request url
     * @param headers The request header
     * @param body    The request body
     * @return The response string
     */
    public static String patch(String url, Map<String, String> headers, String body) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        HttpPatch httpPatch;
        String response;
        BasicCookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookies(Cookie.get());

        try {
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpPatch = new HttpPatch(url);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPatch.addHeader(entry.getKey(), entry.getValue());
            }

            // Update StringEntity to use charset.
            StringEntity se = new StringEntity(body, "utf-8");
            httpPatch.setEntity(se);

            httpResponse = httpClient.execute(httpPatch);

            // Get response.
            HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity, "UTF-8");

            // Get cookies.
            List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
            } else {
                org.apache.http.cookie.Cookie[] cookiesArr = new org.apache.http.cookie.Cookie[cookies.size()];
                for (int i = 0; i < cookies.size(); i++) {
                    cookiesArr[i] = cookies.get(i);
                }
                Cookie.set(cookiesArr);
            }
        } catch (Exception ex) {
            response = null;
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception ex) {
            }
        }

        return response;
    }

    /**
     * Upload file.
     *
     * @param url     The request url
     * @param headers The request headers
     * @param pairs   The key-value pairs of file uploading, i.e. {"file": "path"}
     * @return The response string
     * @throws Exception The exception
     */
    public static String uploadFile(String url, Map<String, String> headers, Map<String, String> pairs) throws Exception {
        String responseStr = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            HttpPost httpPost = new HttpPost(url);

            // Add headers.
            String boundary = UUID.randomUUID().toString().replaceAll("-", "");
            headers.clear();
            headers.put("Content-Type", "multipart/form-data; boundary=" + boundary);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }

            // The multipart entity builder.
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for (String key : pairs.keySet()) {
                if (key.equalsIgnoreCase("file")) {
                    String filePath = pairs.get(key);

                    // Absolute path
                    if (filePath.startsWith("/") || filePath.indexOf(":") > 0) {
                    }
                    // Relative path
                    else {
                        filePath = System.getProperty("user.dir") + File.separator + filePath;
                    }

                    // The file body.
                    FileBody fileBody = new FileBody(new File(filePath));

                    // Add file params.
                    multipartEntityBuilder.setBoundary(boundary);
                    multipartEntityBuilder.addPart(key, fileBody);
                } else {
                    multipartEntityBuilder.addTextBody(key, pairs.get(key), ContentType.APPLICATION_JSON);
                }
            }

            HttpEntity requestEntity = multipartEntityBuilder.build();
            httpPost.setEntity(requestEntity);

            CloseableHttpResponse response = httpClient.execute(httpPost);

            try {
                HttpEntity responseEntity = response.getEntity();
                responseStr = EntityUtils.toString(responseEntity, "UTF-8");
                EntityUtils.consume(responseEntity);
            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }
        return responseStr;
    }

    static class Cookie {

        private static final ThreadLocal<org.apache.http.cookie.Cookie[]> cookieArr = new ThreadLocal<>();

        public static org.apache.http.cookie.Cookie[] get() {
            return cookieArr.get();
        }

        public static void set(org.apache.http.cookie.Cookie[] cookieArr) {
            Cookie.cookieArr.set(cookieArr);
        }

        public static void remove() {
            cookieArr.remove();
        }

    }

}

 

 类似资料: