HTTP请求外部接口工具类(强于使用常规restTemplate)

问题描述:我们经常会遇到请求外部系统接口的业务场景,restTemplate可能会存在请求不通或者获取不到返回报文的情况

解决方案:该工具类中有一个sendPostdataNew方法,使用post 的方式进行数据的请求,会将外部系统的接口返回报文已JSON字符串的形式返回,然后通过调用下面方法就可以将JSON字符串数据解析到我们提前封装好的和外部系统返参Vo一样的实体类中

//resultDate为调用外部接口返回的JSON字符串,ResultVo则是手动封装的接收参数的VO
 ResultVo Vo = JsonUtil.transToRequest(resultData, ResultVo.class);

下面是这个工具类的详细代码,小伙伴们可以取走直用:

@Slf4j
public class HttpUtils {
    private static final int CONNECT_TIMEOUT = 10000;

    /**
     * 使用post 的方式进行数据的请求
     *
     * @param strUrlPath 请求数据路径
     * @param data       请求体参数
     * @return 返回String
     */
    public static String sendPostData(String strUrlPath, String data) {
        return sendPostData(strUrlPath, data, "utf-8");
    }

    /**
     * 使用post 的方式进行数据的请求
     *
     * @param strUrlPath 请求数据路径
     * @param data       请求体参数
     * @return 返回String
     */
    public static String sendPostData(String strUrlPath, String data, String charsetName) {
        HttpURLConnection httpURLConnection = null;
        OutputStream outputStream = null;
        InputStream inptStream = null;
        //获得请求体
        try {
            URL url = new URL(strUrlPath);

            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(50000);
            httpURLConnection.setReadTimeout(50000);


            // 设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            // 设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.getBytes(charsetName).length));
            // 设置编码格式
            httpURLConnection.setRequestProperty("Accept-Charset", charsetName);

            // 获得输出流,向服务器写入数据
            outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data.getBytes(charsetName));

            int response = httpURLConnection.getResponseCode();

            // 请求成功
            if (response == HttpsURLConnection.HTTP_OK) {
                inptStream = httpURLConnection.getInputStream();
                return dealResponseResult(inptStream, charsetName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("http请求异常",e);
            return "";
        } finally {
            if (inptStream != null) {
                try {
                    inptStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return "";
    }

    /**
     * 使用post 的方式进行数据的请求
     *
     * @param strUrlPath 请求数据路径
     * @param data       请求体参数
     * @return 返回String
     */
    public static String sendPostDataNew(String strUrlPath, String data) {

        //获得请求体
        try {
            URL url = new URL(strUrlPath);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(50000);
            httpURLConnection.setReadTimeout(50000);


            // 设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            // 设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.getBytes("utf-8").length));
            // 设置编码格式
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");

            // 获得输出流,向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data.getBytes("utf-8"));

            int response = httpURLConnection.getResponseCode();

            // 请求成功
            if (response == HttpsURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                return dealResponseResult(inptStream, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }
        return "-1";
    }

    /**
     * 处理参数
     */
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    /**
     * 处理返回结果
     */
    public static String dealResponseResult(InputStream inputStream, String charsetName) throws Exception {
        String resultData = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultData = new String(byteArrayOutputStream.toByteArray(), charsetName);
        return resultData;
    }


    public static void main(String[] args) {
        StringBuffer allMsg = new StringBuffer();
        allMsg.append("{");
        allMsg.append("\"policyNo\": \"827122020110100000094\"," +
                "\"InsuredName\": \"sunny1\"," +
                "\"IdentifyNumber\": \"t1526164\"," +
                "\"sign\": \"1234567890123456\"");
        allMsg.append("}");

        System.out.println(allMsg.toString());
        HttpUtils.sendPostData("http://10.69.10.61:8080/mms-middle/Electronic/ElectronicdownPdf", allMsg.toString());

    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java 调用第三方接口通常会使用工具类 RestTemplateRestTemplate 是 Spring 框架提供的一个用于进行 HTTP 请求工具类。它封装了 HTTP 请求的细节,提供了简单的 API 来发送 GET、POST、PUT 和 DELETE 请求,并能够方便地处理返回的响应结果。 使用 RestTemplate 需要先导入相关的依赖包,然后在代码中创建 RestTemplate 的实例。可以通过 RestTemplate 的各种方法来构建不同类型的 HTTP 请求,比如 getForObject、postForObject 等。在方法的参数中需要指定目标接口的 URL 地址,以及可能需要传递的请求参数。 在调用三方接口时,有时需要进行身份验证,可以在请求头中添加认证信息。RestTemplate 的方法中可以通过 HttpHeaders 对象来设置请求头的相关信息。另外,还可以设置请求体的内容格式,比如 JSON、XML 等。 调用接口后,可以通过 RestTemplate 的方法获取响应结果。比如,getForObject 和 postForObject 方法会返回代表响应结果的对象(可以是字符串、对象等)。另外,还可以通过 getForEntity 和 postForEntity 方法获取完整的响应对象,包括响应头、响应体等信息。 在使用 RestTemplate 调用接口时需要注意异常处理。如果调用接口出现异常,可以通过捕获 RestTemplateException 异常来处理。另外,还可以通过设置错误处理器来处理不同类型的错误响应。 总之,RestTemplate 是一个非常实用的工具类,可以方便地进行 Java 对第三方接口的调用。通过它,我们可以发送 HTTP 请求,处理响应结果,并且简化了请求的编写和异常处理的过程。使用 RestTemplate 可以提高开发效率,并且可以与不同的第三方接口进行灵活的集成。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Be explorer

若认可笔者文章,手头富裕望支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值