• HttpUtils-HttpClient3


    因为是应用层的代码,写法通常需要配合其他工具包

    其中cn.seaboot包下的代码,是个人代码封装,功能与函数名同,apache-common中通常有类似函数

            <dependency>
                <groupId>commons-httpclient</groupId>
                <artifactId>commons-httpclient</artifactId>
                <version>3.1</version>
            </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<String, Object> queryString) {
            if (CommonUtils.isEmpty(queryString)) {
                return;
            }
            NameValuePair[] pair = new NameValuePair[queryString.size()];
            int idx = 0;
            for (Entry<String, Object> 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<String,Object> 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<String,Object> 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());
        }
    }
  • 相关阅读:
    P1939 矩阵加速(数列)
    P3390 矩阵快速幂
    快速幂
    1236:区间合并
    1183:病人排队
    1230:寻找平面上的极大点
    1244:和为给定数
    1228 书架
    1222 放苹果
    洛谷5015标题统计
  • 原文地址:https://www.cnblogs.com/chenss15060100790/p/11830750.html
Copyright © 2020-2023  润新知