HttpUtil万能工具类,直接搬用


刚开始接触对接三方的时候真的一头雾水。不知道从何下手。记录一下。
进入对接群。
1.首先拿到最新三方对接文档。
2.仔细阅读文档,包括发送URL。请求方式POST/GET。需要携带的请求头。请求体。请求头有可能是加密后的密文。具体用什么加密算法,包括校验解密。
3.三方都是需要校验获取token。往往校验这种接口,需要有apiKey,secretKey。找到三方对接人申请这些资料。
4.拿到申请的资料之后,先在postman跑一下,拿到token令牌。
5.postman跑通之后。接下来就需要用Java代码模拟用postman发送请求。
我这里用的是httpclient。

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>

这里分享一下我对接遇到的奇奇怪怪的请求。超全万能工具类,帮助和我一样第一次接触三方的新手。
先放一个基础的模板。将情况放到指定位置即可,

package com.xxx.utils;

import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
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.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
/**
 * @author zyx
 * @date 2023/3/3 14:23
 */

public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
    private static RequestConfig requestConfig;

    public HttpUtil() {
    }

    /**
     * 情况方法直接放这里就行
     */
    

    static {
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(60000);
        configBuilder.setSocketTimeout(70000);
        configBuilder.setConnectionRequestTimeout(30000);
        requestConfig = configBuilder.build();
    }
}

POST请求

POST请求,请求体JSON

先以发送POST方式
情况1:请求方式POST,请求体JSON
示例如下:
在这里插入图片描述

/**
     * post,以 application/json 形式
     * @param apiUrl
     * @param json
     * @return
     */
    public static String doPost(String apiUrl, String json) {
        long start = System.currentTimeMillis();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        int statusCode = -999;
        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception var20) {
            logger.info("HttpUtil post error:" + var20.getMessage());
            var20.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException var19) {
                    var19.printStackTrace();
                }
            }

            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }

POST请求,请求体JSON,携带请求头

情况2:发送方式POST,请求体JSON。携带请求头
postman示例如下
在这里插入图片描述
在这里插入图片描述

/**
     * Post方式
     * @param apiUrl
     * @param json json数据
     * @param headerMap 请求头
     * @return
     */
    public static String doPost(String apiUrl, String json, Map<String,String> headerMap) {
        long start = System.currentTimeMillis();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        int statusCode = -999;

        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            //循环增加header
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();
                while(headerIterator.hasNext()){
                    Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
                    httpPost.addHeader(elem.getKey(),elem.getValue());
                }
            }
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception var20) {
            logger.info("HttpUtil post error:" + var20.getMessage());
            var20.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException var19) {
                    var19.printStackTrace();
                }
            }

            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }

POST请求,表单请求体

情况3:发送方式POST。请求体表单
在这里插入图片描述

/**
     * Post请求
     * @param apiUrl 请求链接
     * @param params 请求类型:x-www-form-urlencoded
     * @return
     */
    public static String doPost(String apiUrl, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        String httpStr = null;
        int statusCode = -999;
        //创建http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpPost实例
        HttpPost httpPost = new HttpPost(apiUrl);
        try {
            httpPost.setConfig(requestConfig);
            List<NameValuePair> pairList = new ArrayList();
            Iterator i$ = params.entrySet().iterator();

            while(i$.hasNext()) {
                Entry<String, Object> entry = (Entry)i$.next();
                NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.info("HttpUtil发生错误:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            logger.info("request path:{}, param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, params.toString(), statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }

POST请求,表单请求体+文件上传+请求头

情况4:最为复杂的,发送方式POST。请求头+表单形式发送请求体+文件。
postman如下:
在这里插入图片描述

上传文件,我的情况是,我这个报告文件,在数据库有url。并且已经传到公司文件服务器。对接第三方,现在要把服务器对应url转成文件,上传第三方。
url:http://ip:端口/xxx/2023/03/01/e4d3db2f7d2b4a2b98031192cb590c0c.pdf
先把url的pdf转MultipartFile。

url转MultipartFile,MultipartFile转File工具类。
package com.vkl.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * PDF转换MultipartFile
 *
 * @author MrLi
 * @version 2.0
 */
public class PdfToMultipartFile implements MultipartFile {
    private static final String FILENAME_TEMPLATE = "%s.%s";
    private final byte[] imgContent;
    private final String type;
    private final String fileName;

    private PdfToMultipartFile(byte[] imgContent, String fileName) {
        this.imgContent = imgContent;
        this.fileName = String.format(FILENAME_TEMPLATE, fileName + System.currentTimeMillis(), "pdf");
        this.type = "image";
    }

    @Override
    public String getName() {
        return fileName;
    }

    @Override
    public String getOriginalFilename() {
        return fileName;
    }

    @Override
    public String getContentType() {
        return type;
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(dest);
            fileOutputStream.write(imgContent);
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        }
    }

    public static File MultipartFileToFile(MultipartFile file){
        File toFile = null;
        if("".equals(file) || file.getSize()<=0){
            file = null;
        }else {
            try {
                InputStream inputStream = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(inputStream,toFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream inputStream, File toFile) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(toFile);
            int byteRead = 0;
            byte[] buf = new byte[1024*10];
            while ((byteRead=inputStream.read(buf,0,1024))!=-1){
                os.write(buf,0,byteRead);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static MultipartFile imageUrlToMultipartFile(String fileName, String imageUrl) {
        InputStream fileIs = null;
        ByteArrayOutputStream out = null;
        try {
            if (imageUrl.startsWith("http") || imageUrl.startsWith("https")) {
                URL urlObj = new URL(imageUrl);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(10000);
                urlConnection.setReadTimeout(10000);
                urlConnection.setDoInput(true);
                urlConnection.setUseCaches(false);
                fileIs = urlConnection.getInputStream();
                if (fileIs != null) {
                    out = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fileIs.read(buffer)) > -1) {
                        out.write(buffer, 0, len);
                    }
                    out.flush();
                    byte[] b = out.toByteArray();
                    return new PdfToMultipartFile(b, fileName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileIs != null) {
                try {
                    fileIs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

情况4:方法:

/**
     * @param url url链接
     * @param headMaps 请求头参数
     * @param params 请求体参数
     * @param multipartFile 上传文件,可上传单文件或者多文件
     * @return
     */
    public static String sendMultipartFilePost(String url, Map<String,String> headMaps,
                                               Map<String, Object> params,
                                               Map<String,MultipartFile> multipartFile) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if(headMaps!=null){
                //循环增加header
                Iterator headerIterator = headMaps.entrySet().iterator();
                while(headerIterator.hasNext()){
                    Map.Entry<String,String> elem = (Map.Entry<String, String>) headerIterator.next();
                    httpPost.addHeader(elem.getKey(),elem.getValue());
                }
            }
            //文件上传
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("UTF-8"));
            //浏览器兼容
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //解决中文乱码
            ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if(entry.getValue() == null) {
                    continue;
                }
                //类似浏览器表单提交
                builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
            }
            if(multipartFile != null){
                for (Map.Entry<String, MultipartFile> entry: multipartFile.entrySet()){
                    if(entry.getValue() == null) {
                        continue;
                    }
                    builder.addBinaryBody(entry.getKey(), entry.getValue().getInputStream(), ContentType.MULTIPART_FORM_DATA, entry.getValue().getOriginalFilename());
                }
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            //执行提交
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                //将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("request to:{},param:{},file:{}", new Object[]{url,params.toString()});
        }
        return result;
    }

GET请求

GET请求+拼接参数

发送GET方式
情况1:GET方式,参数
在这里插入图片描述

不要直接在代码写死拼装url。参数用map传。动态获取。
在这里插入图片描述

 /**
     * @param url
     * @param params 带参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        int i = 0;
        for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
            String key = (String)i$.next();
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }

            param.append(key).append("=").append(params.get(key));
        }
        String apiUrl = url + param;
        String result = null;
        //创建一个httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        int statusCode = -999;
        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            HttpResponse response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception var18) {
            logger.info("httputil get error:" + var18.getMessage());
            var18.printStackTrace();
        } finally {
            if (httpClient != null) {
                //关闭流
                HttpClientUtils.closeQuietly(httpClient);
            }

            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
        }

        return result;
    }

GET请求+拼接参数+请求头

情况2:GET请求方式,参数+请求头
在这里插入图片描述

/**
     * 请求方式 Get
     * @param url 请求链接
     * @param params 以 x-www-form-urlencoded
     * @param headerMap 请求头参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> params, Map<String,String> headerMap) {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        int i = 0;

        for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
            String key = (String)i$.next();
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }

            param.append(key).append("=").append(params.get(key));
        }

        String apiUrl = url + param;
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        int statusCode = -999;

        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            //循环增加header
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();
                while(headerIterator.hasNext()){
                    Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
                    httpGet.addHeader(elem.getKey(),elem.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception e) {
            logger.info("HttpUtil发生错误:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                HttpClientUtils.closeQuietly(httpClient);
            }

            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
        }
        return result;
    }

觉得对你有帮助,点赞收藏一波

  • 27
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
httputil是一个常用的网络请求工具类,用于发送HTTP请求并获取响应。在使用httputil工具类发送请求时,可以通过设置请求的cookie来实现身份验证、会话管理等功能。 要设置cookie,首先需要创建一个HttpClient对象。HttpClient用于发送请求并获取响应。在创建HttpClient对象时,可以通过HttpClientBuilder类来设置一些自定义的配置,包括cookie的相关设置。 1. 创建HttpClient对象: ```java HttpClient httpClient = HttpClientBuilder.create().build(); ``` 2. 创建HttpPost或HttpGet对象,设置请求URL和其他相关参数。 3. 设置cookie: ```java CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("cookie_name", "cookie_value"); cookie.setDomain("example.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); ``` 这里创建了一个CookieStore对象,用于存储cookie。然后创建一个BasicClientCookie对象,设置cookie的名称和值。可以通过setDomain()和setPath()方法设置cookie的域和路径。将cookie添加到cookieStore中。 然后创建一个HttpContext对象,并将cookieStore设置为其属性。将HttpContext对象传递给HttpClient对象的execute()方法,执行请求。 4. 发送请求: ```java HttpResponse response = httpClient.execute(httpPost, httpContext); ``` 通过以上步骤,就可以使用httputil工具类发送带有cookie的HTTP请求了。在发送请求时,服务器将根据提供的cookie进行身份验证或会话管理。 需要注意的是,htttputil工具类的具体使用方式可能会因具体的框架和版本而有所不同,可以根据实际情况进行相应的调整。以上是一个基本的示例,供参考使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值