Http请求接口工具类

package com.cic.interfacemodule.util;

import cn.hutool.http.HttpRequest;
import sun.net.www.protocol.http.HttpURLConnection;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.cic.common.util.MyUtils;

/**
 * @author: xuedr
 * @date: 2017-11-27 15:48
 * @description:
 */

public class HttpUtils {

    private static boolean fiddlerDebug = false;
    private static String fiddlerIp = "localhost";
    private static int fiddlerPort = 8888;
    
    


  /**
  *加代理方法
  *
  */    public static String postWithParamsForString(String url,
            List params) {
        HttpHost proxy = new HttpHost("10.192.166.179", 8080, "http");
        HttpPost httpPost = new HttpPost(url);
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setProxy(proxy).build();
        httpPost.setConfig(defaultRequestConfig);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultRequestConfig(defaultRequestConfig).build();
        String s = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            httpPost.setHeader("Content-type",
                    "application/x-www-form-urlencoded");
            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                s = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }





    /**
     *这种方法适用于请求参数必须放在body中的
     *
     */
    public static String postWithParamsForString(String url, List params){
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost =   new HttpPost(url);
        String s = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); 
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                s = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }
    
    /**
     * 模拟doPost请求
     * 
     * @param urlStr
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String doPost(String urlStr, HashMap paramMap) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String paramStr = null;
        if (paramMap != null) {
            paramStr = prepareParam(paramMap);
        }
        conn.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        if (paramMap != null) {
            os.write(paramStr.toString().getBytes("utf-8"));
        }
        os.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        String result = "";
        while ((line = br.readLine()) != null) {
            result += line;
        }
        br.close();
        return result;
    }
    /**
     * 参数解析
     * 
     * @param url
     * @param charset
     * @return
     */
    private static String prepareParam(Map paramMap) {
        StringBuffer sb = new StringBuffer();
        if (paramMap.isEmpty()) {
            return "";
        } else {
            for (Object key : paramMap.keySet()) {
                String value = (String) paramMap.get(key);
                if (sb.length() < 1) {
                    sb.append(key).append("=").append(value);
                } else {
                    sb.append("&").append(key).append("=").append(value);
                }
            }
            return sb.toString();
        }
    }
    /**
     * 方法描述 执行带文件上传的HTTP POST请求。
     *
     * @param strUrl:   请求地址
     * @param fileName: 文件名
     * @param content:  文件内容,类型byte []
     * @return 所代表远程资源的响应结果
     * @throws :
     * @description: The author is Xuedr,Created in 2018-02-26 11:43
     */
    public static String toPost(String strUrl, String fileName, byte[] content, String charset) {
        String result = "";
        charset = MyUtils.isBlank(charset) ? "utf-8" : charset;
        try {
            // 换行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String boundary = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(strUrl);
            Proxy proxy = MyUtils.getProxy();
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", charset);
            conn.setRequestProperty("Content-Type", "multipart/form-data;charset=" + charset + "; boundary=" + boundary);

            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // 上传文件
            //File file = new File(fileName);
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(boundary);
            sb.append(newLine);
            // 文件参数,file参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName
                    + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行,然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);
            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new ByteArrayInputStream(content));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            // 每次读1KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(newLine.getBytes());
            in.close();

            // 定义最后数据分隔线,即--加上BOUNDARY再加上--。
            byte[] endData = (newLine + boundaryPrefix + boundary + boundaryPrefix + newLine)
                    .getBytes();
            // 写上结尾标识
            out.write(endData);
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 向指定URL发送PosT方法的请求
     *
     * @param url:   请求地址
     * @param param: 请求参数,格式name1=value1&name2=value2 的形式
     * @return 所代表远程资源的响应结果
     * @description: The author is xuedr,Created in 2017-11-27 15:48
     */
    public static String toPost(String url, String param) {
        return toPost(url, param, null);
    }

    /**
     * 向指定URL发送PosT方法的请求
     *
     * @param url:    请求地址
     * @param param:  请求参数,格式name1=value1&name2=value2 的形式
     * @param header: 头部参数
     * @return 所代表远程资源的响应结果
     * @description: The author is xuedr,Created in 2017-11-27 15:48
     */
    public static String toPost(String url, String param, Map header) {
        String apiUrl = url;
        if (MyUtils.isNotBlank(param)) {
            apiUrl += "?" + param;
        }
        HttpRequest request = HttpRequest.post(apiUrl);
        // 设置响应头字段
        if (header != null && header.size() > 0) {
            for (String key : header.keySet()) {
                request.header(key, String.valueOf(header.get(key)));
            }
        }

        if (fiddlerDebug) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(fiddlerIp, fiddlerPort));
            request.setProxy(proxy);
        }

        return request.execute().body();
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url:   请求地址
     * @param param: 请求参数,格式name1=value1&name2=value2 的形式
     * @return 所代表远程资源的响应结果
     * @description: The author is Zc,Created in 2017-12-07 8:41
     */
    public static String toGet(String url, String param) {
        return toGet(url, param, null);
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url:    请求地址
     * @param param:  请求参数,格式name1=value1&name2=value2 的形式
     * @param header: 头部参数
     * @return 所代表远程资源的响应结果
     * @description: The author is Zc,Created in 2017-12-07 8:41
     */
    public static String toGet(String url, String param, Map header) {

        String apiUrl = url;
        if (MyUtils.isNotBlank(param)) {
            apiUrl += "?" + param;
        }
        HttpRequest request = HttpRequest.get(apiUrl);
        // 设置响应头字段
        if (header != null && header.size() > 0) {
            for (String key : header.keySet()) {
                request.header(key, String.valueOf(header.get(key)));
            }
        }

        if (fiddlerDebug) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(fiddlerIp, fiddlerPort));
            request.setProxy(proxy);
        }
        return request.execute().body();
    }
}

你可能感兴趣的:(WebService)