HttpUtils-HttpClient3

22472 단어
응용층의 코드이기 때문에, 쓰기 방법은 보통 다른 도구 패키지와 협조해야 한다
그중boot 패키지 아래의 코드는 개인 코드 봉인으로 기능과 함수 이름이 같습니다.apache-common에는 보통 유사한 함수가 있습니다
 
        <dependency>
            <groupId>commons-httpclientgroupId>
            <artifactId>commons-httpclientartifactId>
            <version>3.1version>
        dependency>

 
 
package cn.seaboot.common.net;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

import cn.seaboot.common.bean.P;
import cn.seaboot.common.core.CommonUtils;
import cn.seaboot.common.exception.BizException;

/**
 * HttpClient   
 * @author ChenSS 2018 12 20    5:09:36
 */
public class HttpClientUtils {
    /**
     *     
     */
    @SuppressWarnings("deprecation")
    public static HttpClient getDefaultHttpClient() {
        HttpClientParams defHttpClientParams = new HttpClientParams();
        defHttpClientParams.setConnectionManagerTimeout(P.HTTP_CONNECT_TIMEOUT);
        defHttpClientParams.setSoTimeout(P.HTTP_RESPONSE_TIMEOUT);
        defHttpClientParams.setContentCharset(Charset.defaultCharset().name());
        defHttpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(P.HTTP_MAX_RETRY_COUNT, false));
        defHttpClientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);

        //
        MultiThreadedHttpConnectionManager defConnManager = new MultiThreadedHttpConnectionManager();
        defConnManager.setMaxTotalConnections(P.HTTP_MAX_TOTAL_CONNECTION);
        defConnManager.setMaxConnectionsPerHost(P.HTTP_MAX_CONNECTION_PER_HOST);
        return new HttpClient(defHttpClientParams, defConnManager);
    }

    /**
     * Get
     */
    public static GetMethod getGetMethod(String url) {
        GetMethod get = new GetMethod(url);
        get.setRequestHeader("Connection", "close");
        return get;
    }

    /**
     * Post
     */
    public static PostMethod getPostMethod(String url) {
        PostMethod post = new PostMethod(url);
        post.setRequestHeader("Connection", "close");
        return post;
    }

    /**
     *       
     */
    public static void setMethodParams(HttpMethodBase method, String queryString) {
        method.setQueryString(queryString);
    }

    /**
     *       
     */
    public static void setMethodParams(HttpMethodBase method, Map queryString) {
        if (CommonUtils.isEmpty(queryString)) {
            return;
        }
        NameValuePair[] pair = new NameValuePair[queryString.size()];
        int idx = 0;
        for (Entry entry : queryString.entrySet()) {
            pair[idx++] = new NameValuePair(entry.getKey(), entry.getValue().toString());
        }
        method.setQueryString(pair);
    }

    /**
     *     
     */
    public static void excuteMethod(HttpClient client, HttpMethodBase method) throws HttpException, IOException{
        int code = client.executeMethod(method);
        if (code != HttpStatus.SC_OK) {
            throw new BizException("Request response error:" + code);
        }
    }

    /**
     *   IO 
     * @param client
     * @param method
     * @param is
     */
    public static void doPostInputStream(HttpClient client, PostMethod method, InputStream is) throws HttpException, IOException{
        method.setRequestEntity(new InputStreamRequestEntity(is));
        excuteMethod(client, method);
    }

    /**
     *      
     * @param client
     * @param url
     * @param params
     * @param files
     */
    public static void doPostMultipartFile(HttpClient client, String url, HttpMethodParams params, File... files) throws HttpException, IOException{
        PostMethod method = new PostMethod(url);
        Part[] parts = new Part[files.length];
        File file;
        for (int i = 0; i < parts.length; i++) {
            file = files[i];
            parts[i] = new FilePart(file.getName(), file);
        }
        MultipartRequestEntity entity = new MultipartRequestEntity(parts, params);
        method.setRequestEntity(entity);
        excuteMethod(client, method);
    }

    /**
     *      
     * @param client
     * @param url
     * @param params
     * @param file
     * @throws HttpException -
     * @throws IOException -
     */
    public static void doPostMultipartFile(HttpClient client, String url, HttpMethodParams params, File file) throws HttpException, IOException{
        PostMethod method = new PostMethod(url);
        Part parts = new FilePart(file.getName(), file);
        MultipartRequestEntity entity = new MultipartRequestEntity(new Part[]{parts}, params);
        method.setRequestEntity(entity);
        excuteMethod(client, method);
    }
}

 
package cn.seaboot.plugin.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import cn.seaboot.common.core.Now;
import cn.seaboot.common.net.HttpClientUtils;

/**
 *   POST  
 * @author ChenSS 2019 1 7    4:23:20
 */
public class HttpUtils {
    public static final HttpClient HTTP_CLIENT = HttpClientUtils.getDefaultHttpClient();

    /**
     *   post  
     * @param url
     * @param content        XML
     */
    public static byte[] doWftPost(String url, String content) throws HttpException, IOException {
        PostMethod method = HttpClientUtils.getPostMethod(url);
        method.setRequestHeader("Content-Type", "text/xml;utf-8");
        method.setRequestEntity(new StringRequestEntity(content, null, "UTF-8"));
        HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
        return method.getResponseBody();
    }
    
    
    /**
     *   post  
     * @param url
     * @param content        XML
     */
    public static String doHkPost(String url, String content) throws HttpException, IOException {
        PostMethod method = HttpClientUtils.getPostMethod(url);
        method.setRequestHeader("Content-Type", "application/json;utf-8");
        method.setRequestEntity(new StringRequestEntity(content, null, "UTF-8"));
        HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
        return method.getResponseBodyAsString();
    }
    
    
    /**
     *   post  
     * @param url
     */
    public static String doPost(String url, Map map) throws HttpException, IOException {
        PostMethod method = HttpClientUtils.getPostMethod(url);
        HttpClientUtils.setMethodParams(method, map);
        HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
        return method.getResponseBodyAsString();
    }
    
    public static void main(String[] args) throws IOException {g";
            PostMethod method = HttpClientUtils.getPostMethod(url);
//            method.setRequestHeader("Content-Type", "application/json;utf-8");
            Map map = new HashMap<>(); 
            map.put("uid",1);  
            map.put("userId",1);  
            map.put("msg","----------------");  
            map.put("createDate",Now.dateTime());  
            HttpClientUtils.setMethodParams(method, map);
//            HttpClientUtils.setMethodParams(method, "content='www.baidu.com'&imgExtName='jpg'&size='5'");
            HttpClientUtils.excuteMethod(HTTP_CLIENT, method);
            System.out.println(method.getResponseBodyAsString());
    }
}

좋은 웹페이지 즐겨찾기