All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.net.wanmo.apache.http.HttpUtil Maven / Gradle / Ivy

There is a newer version: 1.0.4
Show newest version
package cn.net.wanmo.apache.http;


import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Objects;

public class HttpUtil extends HttpBase {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private static HttpUtil create() {
        HttpUtil http = new HttpUtil();
        http.client = HttpClients.createDefault();
        return http;
    }

    public static HttpUtil get(String url) {
        HttpUtil http = create();

        http.method = Method.GET;
        http.url = url;
        http.httpGet = new HttpGet(url);

        return http;
    }

    public static HttpUtil post(String url) {
        HttpUtil http = create();

        http.method = Method.POST;
        http.url = url;
        http.httpPost = new HttpPost(url);

        http.entityBuilder = EntityBuilder.create();
        http.multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); // 解决文件上传中文名乱码

        return http;
    }

    public HttpResult execute() throws IOException {
        switch (method) {
            case GET: {
                {
                    RequestConfig requestConfig = HttpConfig.build(this.config);
                    this.httpGet.setConfig(requestConfig);
                }

                if (this.paramsList.isEmpty() == false) {
                    String s = EntityUtils.toString(new UrlEncodedFormEntity(this.paramsList, Consts.UTF_8));
                    if (this.url.contains("?")) {
                        this.url = this.url + "&" + s;
                    } else {
                        this.url = this.url + "?" + s;
                    }
                    logger.debug("Get Url = {}", url);
                    this.httpGet.setURI(URI.create(this.url));
                }

                this.response = this.client.execute(this.httpGet);
                break;
            }
            case POST: {
                {
                    RequestConfig requestConfig = HttpConfig.build(this.config);
                    this.httpPost.setConfig(requestConfig);
                }

                if (Objects.nonNull(this.body)) { // 请求体
                    this.httpPost.setEntity(new StringEntity(this.body, ContentType.APPLICATION_JSON.withCharset(Consts.UTF_8)));
                }

                if (this.paramsList.isEmpty() == false) { // 请求参数
                    if (this.isMultipart) {
                        for (BasicNameValuePair pair : this.paramsList) {
                            this.multipartEntityBuilder.addTextBody(pair.getName(), pair.getValue(), ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8));
                        }
                    } else {
                        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(this.paramsList, Consts.UTF_8);
                        this.httpPost.setEntity(urlEncodedFormEntity);
                    }
                }

                if (this.isMultipart) {
                    HttpEntity entity = this.multipartEntityBuilder.build();
                    this.httpPost.setEntity(entity);
                }
                this.response = this.client.execute(this.httpPost);
                break;
            }
            default:
                logger.error("未知的请求方式");
        }

        return new HttpResult(this.response);
    }



    public HttpUtil header(String name, Object value) {
        switch (this.method) {
            case GET: {
                this.httpGet.addHeader(name, String.valueOf(value));
                break;
            }
            case POST: {
                this.httpPost.addHeader(name, String.valueOf(value));
                break;
            }
            default: {
                logger.error("未知的请求方式");
            }
        }

        return this;
    }

    public HttpUtil form(String name, Object value) {
        BasicNameValuePair pair = new BasicNameValuePair(name, String.valueOf(value));
        this.paramsList.add(pair);
        return this;
    }

    public HttpUtil form(String name, File file) {
        return form(name, file, file.getName());
    }

    public HttpUtil form(String name, File file, String filename) {
        this.isMultipart = true;
        multipartEntityBuilder.addBinaryBody(name, file, ContentType.MULTIPART_FORM_DATA, filename);
        return this;
    }

    public HttpUtil body(String body) {
        this.body = body;
        return this;
    }

    // ======================================================================

    public HttpUtil socketTimeout(int timeout) {
        this.config.setSocketTimeout(timeout);
        return this;
    }
    public HttpUtil connectTimeout(int timeout) {
        this.config.setConnectTimeout(timeout);
        return this;
    }

    public HttpUtil() {
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy