HttpUtils工具类

近期项目频繁出现http请求出现乱码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package io.renren.common.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.config.ApiConfig;
import io.renren.modules.sys.dao.SysParamsDao;
import io.renren.modules.sys.entity.SysParamsEntity;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
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.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class HttpUtils {
    private static HttpUtils httpUtils;
    @Resource
    SysParamsDao sysParamsDao;
    @Autowired
    ApiConfig apiConfig;
    private List<SysParamsEntity> params;

    public HttpUtils() {
    }

    /**
     * POST请求
     *
     * @param httpUrl
     * @param param   (请求参数)
     * @return
     * @author hlj
     */
    public static String doPost(String httpUrl, String param) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type",  "application/json;charset=UTF-8");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes("UTF-8"));
            // 通过连接对象获取一个输入流,向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    public static void main(String[] args) {
        Map map = (new HttpUtils()).sendPost("http://api.sandbox.adbright.cn/api/v1/finance/list_change_record.do", new ConcurrentHashMap() {
            {
                this.put("page", 1);
            }
        });
        System.out.println(map);
    }

   
    @PostConstruct
    public void init() {
        httpUtils = this;
        httpUtils.params = httpUtils.sysParamsDao.selectList(new QueryWrapper() {
            {
                this.eq("param_type", 1);
            }
        });
    }

    public HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
        HttpClient httpClient = this.wrapClient(host);
        HttpGet request = new HttpGet(this.buildUrl(host, path, querys));
        Iterator var8 = headers.entrySet().iterator();

        while (var8.hasNext()) {
            Entry<String, String> e = (Entry) var8.next();
            request.addHeader((String) e.getKey(), (String) e.getValue());
        }

        return httpClient.execute(request);
    }

    public Map sendPost(String url) {
        return this.sendPost(url, new ConcurrentHashMap());
    }

    public Map sendPost(String url, Map<String, Object> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        long time = (new Date()).getTime();
        String clientId = ((SysParamsEntity) httpUtils.params.stream().filter((o) -> {
            return o.getParamCode().equals("client_id");
        }).findFirst().get()).getParamValue();
        String clientSecret = ((SysParamsEntity) httpUtils.params.stream().filter((o) -> {
            return o.getParamCode().equals("client_secret");
        }).findFirst().get()).getParamValue();
        paramMap.put("ts", time);
        paramMap.put("client_id", clientId);
        paramMap.put("sign", DigestUtils.md5Hex(clientId + "," + time + "," + clientSecret));
        String param = "";

        String key;
        for (Iterator it = paramMap.keySet().iterator(); it.hasNext(); param = param + key + "=" + paramMap.get(key) + "&") {
            key = (String) it.next();
        }

        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();

            String line;
            for (in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); (line = in.readLine()) != null; result = result + line) {
                System.out.println(line);
            }
        } catch (Exception var23) {
            var23.printStackTrace();
            System.out.println(var23);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var22) {
                var22.printStackTrace();
            }

        }

        return (Map) JSON.parseObject(result, Map.class);
    }

    public HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception {
        HttpClient httpClient = this.wrapClient(host);
        HttpPost request = new HttpPost(this.buildUrl(host, path, querys));
        Iterator var9 = headers.entrySet().iterator();

        while (var9.hasNext()) {
            Entry<String, String> e = (Entry) var9.next();
            request.addHeader((String) e.getKey(), (String) e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList();
            Iterator var12 = bodys.keySet().iterator();

            while (var12.hasNext()) {
                String key = (String) var12.next();
                nameValuePairList.add(new BasicNameValuePair(key, (String) 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);
    }

    public HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
        HttpClient httpClient = this.wrapClient(host);
        HttpPost request = new HttpPost(this.buildUrl(host, path, querys));
        Iterator var9 = headers.entrySet().iterator();

        while (var9.hasNext()) {
            Entry<String, String> e = (Entry) var9.next();
            request.addHeader((String) e.getKey(), (String) e.getValue());
        }

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

        return httpClient.execute(request);
    }

    public HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
        HttpClient httpClient = this.wrapClient(host);
        HttpPost request = new HttpPost(this.buildUrl(host, path, querys));
        Iterator var9 = headers.entrySet().iterator();

        while (var9.hasNext()) {
            Entry<String, String> e = (Entry) var9.next();
            request.addHeader((String) e.getKey(), (String) e.getValue());
        }

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

        return httpClient.execute(request);
    }

    public HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
        HttpClient httpClient = this.wrapClient(host);
        HttpPut request = new HttpPut(this.buildUrl(host, path, querys));
        Iterator var9 = headers.entrySet().iterator();

        while (var9.hasNext()) {
            Entry<String, String> e = (Entry) var9.next();
            request.addHeader((String) e.getKey(), (String) e.getValue());
        }

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

        return httpClient.execute(request);
    }

    public HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
        HttpClient httpClient = this.wrapClient(host);
        HttpPut request = new HttpPut(this.buildUrl(host, path, querys));
        Iterator var9 = headers.entrySet().iterator();

        while (var9.hasNext()) {
            Entry<String, String> e = (Entry) var9.next();
            request.addHeader((String) e.getKey(), (String) e.getValue());
        }

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

        return httpClient.execute(request);
    }

    public HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
        HttpClient httpClient = this.wrapClient(host);
        HttpDelete request = new HttpDelete(this.buildUrl(host, path, querys));
        Iterator var8 = headers.entrySet().iterator();

        while (var8.hasNext()) {
            Entry<String, String> e = (Entry) var8.next();
            request.addHeader((String) e.getKey(), (String) e.getValue());
        }

        return httpClient.execute(request);
    }

    private String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }

        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            Iterator var6 = querys.entrySet().iterator();

            while (var6.hasNext()) {
                Entry<String, String> query = (Entry) var6.next();
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }

                if (StringUtils.isBlank((CharSequence) query.getKey()) && !StringUtils.isBlank((CharSequence) query.getValue())) {
                    sbQuery.append((String) query.getValue());
                }

                if (!StringUtils.isBlank((CharSequence) query.getKey())) {
                    sbQuery.append((String) query.getKey());
                    if (!StringUtils.isBlank((CharSequence) query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode((String) query.getValue(), "utf-8"));
                    }
                }
            }

            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

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

        return httpClient;
    }

    private void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            ctx.init((KeyManager[]) null, new TrustManager[]{tm}, (SecureRandom) 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 (KeyManagementException var7) {
            throw new RuntimeException(var7);
        } catch (NoSuchAlgorithmException var8) {
            throw new RuntimeException(var8);
        }
    }
    /**
     * get请求
     * @param httpUrl 请求加参数的字符串
     * @author hlj
     * @return
     */
    public static String sendGet(String httpUrl){
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值