JAVA实现HTTP请求的

一、maven依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.4</version>
</dependency>

二、拼接请求的方法

//https请求构建
private static HttpClient wrapClient(String host) {
    HttpClient httpClient = new DefaultHttpClient();
    if (host.startsWith("https://")) {
        sslClient(httpClient);
    }
    return httpClient;
}

private static void sslClient(HttpClient httpClient) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry registry = ccm.getSchemeRegistry();
        registry.register(new Scheme("https", 443, ssf));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

//拼接请求的地址
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
    StringBuilder sbUrl = new StringBuilder();
    sbUrl.append(host);
    if (StringUtils.isNotBlank(path)) {
        sbUrl.append(path);
    }
    if (null != querys) {
        StringBuilder sbQuery = new StringBuilder();
        for (Map.Entry<String, String> query : querys.entrySet()) {
            if (sbQuery.length() > 0) {
                sbQuery.append("&");
            }
            if (StringUtils.isBlank(query.getKey()) && StringUtils.isNotBlank(query.getValue())) {
                sbQuery.append(query.getValue());
            }
            if (StringUtils.isNotBlank(query.getKey())) {
                sbQuery.append(query.getKey());
                if (StringUtils.isNotBlank(query.getValue())) {
                    sbQuery.append("=");
                    sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                }
            }
        }
        if (sbQuery.length() > 0) {
            sbUrl.append("?").append(sbQuery);
        }
    }
    return sbUrl.toString();
}

三、GET请求

/**
     * GET请求一
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @return
     */
public static HttpResponse doGet(String host, String path,
                                 Map<String, String> headers,
                                 Map<String, String> querys) throws Exception {
    HttpClient httpClient = wrapClient(host);
    HttpGet request = new HttpGet(buildUrl(host, path, querys));
    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(header.getKey(), header.getValue());
    }
    return httpClient.execute(request);

}

/**
     * GET请求二 请求链接和Cookie
     *
     * @param url
     * @param cookie
     * @return
     */
public static String doGet(String url, String cookie) {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        URI uri = new URI(url);
        HttpGet get = new HttpGet(uri);
        get.setHeader("Cookie", cookie);
        //执行请求
        HttpResponse response = client.execute(get);

        if (response.getStatusLine().getStatusCode() == 200) {
            StringBuffer buffer = new StringBuffer();
            InputStream in = null;
            try {
                in = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    in.close();
                }
            }
            return buffer.toString();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

四、POST请求

/**
     * POST请求,适合form-data传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  Map<String, String> bodys) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));

    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(header.getKey(), header.getValue());
    }
    if (bodys != null) {
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        for (String key : bodys.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
        formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
        request.setEntity(formEntity);
    }

    return httpClient.execute(request);
}

/**
     * POST请求,适合json传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  String body) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));

    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(header.getKey(), header.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }
    return httpClient.execute(request);
}


/**
     * POST请求,适合字节传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  byte[] body) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));

    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(header.getKey(), header.getValue());
    }

    if (body != null) {
        request.setEntity(new ByteArrayEntity(body));
    }
    return httpClient.execute(request);
}

/**
     * post请求传参是文件
     * @param host
     * @param path
     * @param fileMap
     * @param fileNameMap
     * @param headers
     * @param bodys
     * @return
     * @throws Exception
     */
public static HttpResponse doPost(String host, String path,
                                  Map<String, File> fileMap,
                                  Map<String ,String> fileNameMap,
                                  Map<String, String> headers,
                                  Map<String, String> bodys) throws Exception {
    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post  = new HttpPost(host + path);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (Map.Entry<String, String> header : headers.entrySet()) {
            post.addHeader(header.getKey(), header.getValue());
        }

        //拼接文件的请求体
        for (Map.Entry<String, File> fileEntry : fileMap.entrySet()) {
            String defaultName = "defaultName";
            String fileName = fileNameMap.get(fileEntry.getKey());
            if (StringUtils.isNotBlank(fileName)){
                defaultName = fileName;
            }
            builder.setCharset(StandardCharsets.UTF_8)
                .addBinaryBody(fileEntry.getKey() , fileEntry.getValue() , ContentType.MULTIPART_FORM_DATA ,defaultName);
        }

        //拼接正常参数的请求体
        if(bodys != null){
            for (Map.Entry<String, String> body : bodys.entrySet()) {
                builder.addTextBody(body.getKey() , body.getValue());
            }
        }

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        return response;

    }catch (Exception e){
        e.printStackTrace();
    }
    return null;

}

五、PUT和DELETE请求

/**
     * PUT请求,适合json传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
public static HttpResponse doPut(String host, String path, String method,
                                 Map<String, String> headers,
                                 Map<String, String> querys,
                                 String body) throws Exception {
    HttpClient httpClient = wrapClient(host);
    HttpPut request = new HttpPut(buildUrl(host, path, querys));

    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(header.getKey(), header.getValue());
    }
    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }
    return httpClient.execute(request);
}

/**
     * DELETE请求
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @return
     */
public static HttpResponse doDelete(String host, String path,
                                    Map<String, String> headers,
                                    Map<String, String> querys) throws Exception {
    HttpClient httpClient = wrapClient(host);
    HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(header.getKey(), header.getValue());
    }
    return httpClient.execute(request);

}

六、完整的工具类代码

package com.it520.bookkeepingcommon.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    /**
     * GET请求一
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @return
     */
    public static HttpResponse doGet(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.addHeader(header.getKey(), header.getValue());
        }
        return httpClient.execute(request);

    }

    /**
     * GET请求二 请求链接和Cookie
     *
     * @param url
     * @param cookie
     * @return
     */
    public static String doGet(String url, String cookie) {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            URI uri = new URI(url);
            HttpGet get = new HttpGet(uri);
            get.setHeader("Cookie", cookie);
            //执行请求
            HttpResponse response = client.execute(get);

            if (response.getStatusLine().getStatusCode() == 200) {
                StringBuffer buffer = new StringBuffer();
                InputStream in = null;
                try {
                    in = response.getEntity().getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        in.close();
                    }
                }
                return buffer.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * POST请求,适合form-data传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));

        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.addHeader(header.getKey(), header.getValue());
        }
        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * POST请求,适合json传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));

        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.addHeader(header.getKey(), header.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
    }


    /**
     * POST请求,适合字节传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));

        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.addHeader(header.getKey(), header.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
    }

    /**
     * post请求传参是文件
     * @param host
     * @param path
     * @param fileMap
     * @param fileNameMap
     * @param headers
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path,
                                      Map<String, File> fileMap,
                                      Map<String ,String> fileNameMap,
                                      Map<String, String> headers,
                                      Map<String, String> bodys) throws Exception {
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post  = new HttpPost(host + path);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Map.Entry<String, String> header : headers.entrySet()) {
                post.addHeader(header.getKey(), header.getValue());
            }

            //拼接文件的请求体
            for (Map.Entry<String, File> fileEntry : fileMap.entrySet()) {
                String defaultName = "defaultName";
                String fileName = fileNameMap.get(fileEntry.getKey());
                if (StringUtils.isNotBlank(fileName)){
                    defaultName = fileName;
                }
                builder.setCharset(StandardCharsets.UTF_8)
                        .addBinaryBody(fileEntry.getKey() , fileEntry.getValue() , ContentType.MULTIPART_FORM_DATA ,defaultName);
            }

            //拼接正常参数的请求体
            if(bodys != null){
                for (Map.Entry<String, String> body : bodys.entrySet()) {
                    builder.addTextBody(body.getKey() , body.getValue());
                }
            }

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            return response;

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

    /**
     * PUT请求,适合json传参
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body) throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPut request = new HttpPut(buildUrl(host, path, querys));

        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.addHeader(header.getKey(), header.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
    }

    /**
     * DELETE请求
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @return
     */
    public static HttpResponse doDelete(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.addHeader(header.getKey(), header.getValue());
        }
        return httpClient.execute(request);

    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }
        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (StringUtils.isNotBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (sbQuery.length() > 0) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && StringUtils.isNotBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (StringUtils.isNotBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (StringUtils.isNotBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (sbQuery.length() > 0) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        return sbUrl.toString();
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值