HttpUtils

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};

    public static boolean isMSBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true;
        }
        return false;
    }

    public static String doPost(String url, Map<String, String> mapParams) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            //封装请求参数
            if (mapParams != null) {
                List<BasicNameValuePair> list = new ArrayList<>();
                for (Map.Entry<String, String> entry : mapParams.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, "utf-8");
                formEntity.setContentType("Content-Type:application/json");
                httpPost.setEntity(formEntity);
            }

            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String doPost(String url, String jsonParam, String token) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            if (StringUtils.isNotBlank(token))
                httpPost.setHeader("Authorization", token);

            StringEntity stringEntity = new StringEntity(jsonParam);
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");

            httpPost.setEntity(stringEntity);

            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json方式请求,下载图片
     *
     * @param url
     * @param params
     * @param dirPath
     * @param fileName
     */
    public static void doPost(String url, Map<String, Object> params, String dirPath, String fileName) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            String body = JSON.toJSONString(params);
            StringEntity stringEntity = new StringEntity(body);
            stringEntity.setContentType("image/png");
            httpPost.setEntity(stringEntity);

            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                InputStream in = response.getEntity().getContent();
                savePicToDisk(in, dirPath, fileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String doGet(String url, Map<String, String> mapParams) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //封装请求参数
            if (mapParams != null) {
                List<BasicNameValuePair> list = new ArrayList<>();
                for (Map.Entry<String, String> entry : mapParams.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
            }

            HttpGet httpget = new HttpGet(url);
            try (CloseableHttpResponse response = httpclient.execute(httpget)) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建文件
     *
     * @param in
     * @param dirPath
     * @param fileName
     */
    private static void savePicToDisk(InputStream in, String dirPath, String fileName) {
        try {
            File dir = new File(dirPath);
            if (!dir.exists()) {
                boolean bool = dir.mkdirs();
            }

            File file = new File(dirPath, fileName);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int nRead = 0;
            while ((nRead = in.read(b)) != -1) {
                fos.write(b, 0, nRead);
            }

            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> map = new HashMap<>();
        map.put("appid", "APPID");
        map.put("secret", "SECRET");
        map.put("js_code", "JSCODE");
        map.put("grant_type", "authorization_code");
        JSONObject jsonObject = JSON.parseObject(HttpUtils.doGet(url, map));
        if (jsonObject != null) {
            System.out.println(jsonObject.toJSONString());
            if (jsonObject.containsKey("openid")) {
                String openid = jsonObject.getString("openid");
                String sessionKey = jsonObject.getString("session_key");
            }
        }
    }
}

 

                boolean isMSIE = HttpUtils.isMSBrowser(request);
                if (isMSIE) {
                    //IE浏览器的乱码问题解决
                    file_name = URLEncoder.encode(filename, "UTF-8");
                } else {
                   //万能乱码问题解决
                    file_name = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
                }

 

HttpClient关闭控制台的DEBUG输出

resources下添加logback.xml

<configuration debug="false">
    <!--以下三行一定注释掉,否则还会打印部分debug日志,o.apache.commons.httpclient.HttpClient-->
    <!--<logger name="org.apache" level="DEBUG" />-->
    <!--<logger name="org.apache.http.wire" level="DEBUG" />-->
    <!--<logger name="org.apache.http.headers" level="INFO" />-->

    <property name="CONSOLE_LOG_PATTERN"
              value="%date{yyyy-MM-dd HH:mm:ss}  %highlight(%-5level) %magenta(%-4relative) --- [%yellow(%15.15thread)] %cyan(%-40.40logger{39}) : %msg%n"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>

    <root level="ERROR">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

 

posted on 2020-04-03 14:33  1zfang1  阅读(1267)  评论(0编辑  收藏  举报

导航