封装http请求

在开发当中调其他系统请求或模拟前端调请求有时会使用到http请求,但java原生类还是比较难用的,一般会自己封装一下,本文展示http请求的一般封装,可以直接拷贝使用。

package com.zqsign.app.privatearbitrate.util;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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.util.EntityUtils;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {


        // 创建Httpclient对象
        CloseableHttpClient httpclient = createCustomClient();

        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url, String body) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (body != null) {
                httpPost.setEntity(new StringEntity(body, "utf-8"));
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, (String) null);
    }

    public static String doPostJson(String url, String json, Header... headers) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            //添加请求头
            if (headers != null && headers.length > 0) {
                for (Header header : headers) {
                    if (header != null) {
                        httpPost.addHeader(header);
                    }
                }
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200) {
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }else {
            	resultString = "调用服务端异常,请联系相关人员";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static CloseableHttpClient createCustomClient() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(120 * 1000)
                .setConnectTimeout(120 * 1000)
                .setConnectionRequestTimeout(120 * 1000)
                .setStaleConnectionCheckEnabled(true)
                .build();

        return HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    }
}

使用:

  @Test
    public void evidenceTest() {

        long a = System.currentTimeMillis();
        Map<String,Object> param = getParam("evidence");
        long b = System.currentTimeMillis();
        System.out.println("拼接数据时间:" + (b-a));
        String str = JSON.toJSONString(param);
        String sign = RsaSign.sign(str, TENANT_PRIVATE_KEY);
        BasicHeader header = new BasicHeader("sign_val", sign);
        System.out.println(str);

        long start = System.currentTimeMillis();
        String res = HttpClientUtil.doPostJson("http://localhost:8080/web/trade-upload", JSON.toJSONString(param),header);
        long end = System.currentTimeMillis();

        System.out.println("请求接口时间:" + (end-start));
        System.out.println("接口反馈信息:" + res);

    }

当然,现在已经不用自己封装了,spring3.0之后提供了org.springframework.web.client.RestTemplate类来供我们发送http请求。

猜你喜欢

转载自blog.csdn.net/shidebin/article/details/85063711