JavaUtils:HTTP请求

pom.xml

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.5.2</version>
		</dependency>

HttpUtil

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class HttpUtil {

    /**
     * 功能描述:
     * <JSON>
     *
     * @param  urlPath 1
     * @param  jsonStr 2
     * @param  headers 3
     * @param  readTimeOut 4
     * @return java.lang.String
     * @author zhoulipu
     * @date   2019/9/16 20:09
     */
    public static String post(String urlPath, String jsonStr, Map<String, String> headers, int readTimeOut) {
        String result = "";
        BufferedReader reader = null;
        long startTime = System.currentTimeMillis();
        boolean resCode = true;
        JSONObject json;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(readTimeOut);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("accept", "application/json");
            if (headers != null && headers.size() > 0) {
                headers.forEach((k, v) -> {
                    conn.setRequestProperty(k, v);
                });
            }
            if (jsonStr != null && !TextUtils.isEmpty(jsonStr)) {
                byte[] bytes = jsonStr.getBytes();
                conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
                OutputStream out = conn.getOutputStream();
                out.write(jsonStr.getBytes());
                out.flush();
                out.close();
            }
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    result = result + line;
                }
            } else {
                resCode = false;
            }
        } catch (Exception var24) {
            var24.printStackTrace();
        } finally {
            if (resCode) {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception var22) {
                        var22.printStackTrace();
                    }
                }
                long endTime = System.currentTimeMillis();
                json = new JSONObject();
                json.put("url", urlPath);
                json.put("req", jsonStr);
                json.put("res", result);
                json.put("time", endTime - startTime);
                System.out.println("[http] : " + json.toJSONString());
            }
        }
        return result;
    }

    /**
     * 功能描述:
     * <Map>
     *
     * @param  url 1
     * @param  paramMap 2
     * @param  headers 3
     * @param  readTimeOut 4
     * @return java.lang.String
     * @author zhoulipu
     * @date   2019/9/16 20:09
     */
    public static String post(String url, Map<String, Object> paramMap, Map<String, String> headers, int readTimeOut) {
        CloseableHttpClient client;
        CloseableHttpResponse response = null;
        String result = "";
        long startTime = System.currentTimeMillis();
        client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(readTimeOut).build();
        post.setConfig(requestConfig);
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        if (headers != null && headers.size() > 0) {
            headers.forEach((k, v) -> {
                post.addHeader(k, v);
            });
        }
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> pairs = new ArrayList();
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            Iterator iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = (Map.Entry) iterator.next();
                pairs.add(new BasicNameValuePair((String) mapEntry.getKey(), mapEntry.getValue().toString()));
            }
            try {
                post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
            } catch (UnsupportedEncodingException var30) {
                var30.printStackTrace();
            }
        }
        try {
            response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException var28) {
            var28.printStackTrace();
        } catch (IOException var29) {
            var29.getStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException var27) {
                    var27.getStackTrace();
                }
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException var26) {
                    var26.getStackTrace();
                }
            }
        }
        long endTime = System.currentTimeMillis();
        JSONObject json = new JSONObject();
        json.put("url", url);
        json.put("req", JSONObject.toJSONString(paramMap));
        json.put("res", result);
        json.put("time", endTime - startTime);
        System.out.println("http:" + json.toJSONString());
        return result;
    }

    /**
     * 功能描述:
     * <form-data>
     *
     * @param  url 1
     * @param  paramMap 2
     * @param  fileMap 3
     * @param  headers 4
     * @param  readTimeOut 5
     * @return java.lang.String
     * @author zhoulipu
     * @date   2019/9/16 20:09
     */
    public static String post(String url, Map<String, String> paramMap, Map<String, String> fileMap, Map<String, String> headers, int readTimeOut) {
        CloseableHttpClient client;
        CloseableHttpResponse response = null;
        String result = "";
        long startTime = System.currentTimeMillis();
        client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(readTimeOut).build();
        post.setConfig(requestConfig);
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        if (headers != null && headers.size() > 0) {
            headers.forEach((k, v) -> {
                post.addHeader(k, v);
            });
        }
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (null != fileMap && fileMap.size() > 0) {
            Set<Map.Entry<String, String>> entrySet = fileMap.entrySet();
            Iterator iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = (Map.Entry) iterator.next();
                builder.addPart(mapEntry.getKey(),  new FileBody(new File(mapEntry.getValue().toString())));
            }
        }
        if (null != paramMap && paramMap.size() > 0) {
            Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
            Iterator iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = (Map.Entry) iterator.next();
                builder.addTextBody(mapEntry.getKey(),  mapEntry.getValue().toString());
            }
        }
        HttpEntity reqEntity = builder.build();
        post.setEntity(reqEntity);
        try {
            response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException var28) {
            var28.printStackTrace();
        } catch (IOException var29) {
            var29.getStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException var27) {
                    var27.getStackTrace();
                }
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException var26) {
                    var26.getStackTrace();
                }
            }
        }
        long endTime = System.currentTimeMillis();
        JSONObject json = new JSONObject();
        json.put("url", url);
        json.put("req", JSONObject.toJSONString(paramMap));
        json.put("res", result);
        json.put("time", endTime - startTime);
        System.out.println("http:" + json.toJSONString());
        return result;
    }

    /**
     * 功能描述:
     * <Get>
     *
     * @param  url 1
     * @param  readTimeOut 2
     * @return java.lang.String
     * @author zhoulipu
     * @date   2019/9/16 20:10
     */
    public static String doGet(String url, int readTimeOut) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(500).setConnectionRequestTimeout(500).setSocketTimeout(readTimeOut).build();
            httpGet.setConfig(requestConfig);
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException var18) {
            var18.printStackTrace();
        } catch (IOException var19) {
            var19.getStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException var17) {
                    var17.getStackTrace();
                }
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException var16) {
                    var16.getStackTrace();
                }
            }
        }
        return result;
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值