java发起http、https请求,并携带cookie、header,post参数放body并可选关闭ssl证书验证,高可用版

news/2025/1/11 4:14:42/

公司有个需求是发起https请求对接国家数据接口,需要带header、cookie,并关闭ssl证书验证,搜了很多文章,都说用HttpsURLConnection发起请求,但不知为啥在封装body参数的时候一直报400封装出错,也欢迎指出不足。遂找了这古代的方法,方法虽老但能解决实际问题且不用导包。

HttpsURLConnection报错方法示例:

			// 发起HTTPS POST请求URL url = new URL("https://example.com/api/resource");connection = (HttpsURLConnection) url.openConnection();// 设置请求方法为POSTconnection.setRequestMethod("POST");connection.setDoOutput(true); // 允许写入请求体connection.setRequestProperty("Content-Type", "application/json");// 封装请求体参数,这里假设参数是一个 JSON 对象String requestBody = "{\"param1\":\"value1\", \"param2\":\"value2\"}";//此处封装body参数一直报错try (OutputStream os = connection.getOutputStream()) {byte[] input = requestBody.getBytes("utf-8");os.write(input, 0, input.length);}// 获取响应int responseCode = connection.getResponseCode();System.out.println("Response Code: " + responseCode);BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;StringBuilder response = new StringBuilder();while ((line = reader.readLine()) != null) {response.append(line);}reader.close();System.out.println("Response: " + response.toString());

使用方法(其实cookie也是在header里面):

1.创建默认证书(可选)

    /*** 创建默认证书** @return*/public static CloseableHttpClient createSSLClientDefault() {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (Exception e) {e.printStackTrace();}return HttpClients.createDefault();}

2.post请求:

   public static String dopost(String reqUrl, String json, Map<String, String> headerMap) {String strResult = "";CloseableHttpResponse response = null;CloseableHttpClient httpClient = null;if (reqUrl.startsWith("https")) {//可选httpClient = createSSLClientDefault();} else {httpClient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(1 * 60 * 1000).setConnectTimeout(1000).setConnectionRequestTimeout(1000).build()).build();}HttpEntity httpEntity = null;try {HttpPost httpPost = new HttpPost(reqUrl);if (headerMap != null) {headerMap.forEach((k, v) -> httpPost.addHeader(k, v));}StringEntity entity = new StringEntity(json, "UTF-8");//解决中文乱码问题entity.setContentType("application/json");httpPost.setEntity(entity);response = httpClient.execute(httpPost, HttpClientContext.create());int status = response.getStatusLine().getStatusCode();httpEntity = response.getEntity();if (status == 200) {String string = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);return EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);} else {log.error(reqUrl + " 请求错误:\r\t" + EntityUtils.toString(httpEntity, StandardCharsets.UTF_8));}return strResult;} catch (IOException e) {e.printStackTrace();} finally {try {if (httpEntity != null) {EntityUtils.consume(httpEntity);}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}return strResult;}

3.get请求:

    public static ResultVo sendHttpsRequest(String url, String requestMethod, Stringparam, Map<String, String> headers, String cookieStr) {ResultVo vo = new ResultVo();StringBuilder result = new StringBuilder();try {//屏蔽证书验证SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}}}, new SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();// GET/POSTconn.setRequestMethod(requestMethod);
//            conn.setDoOutput(true);conn.setDoInput(true);if ("POST".equals(requestMethod)) {try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {wr.writeBytes(param);wr.flush();}conn.setRequestProperty("Content-Type", "application/json");} else {if (null != param) {OutputStream outputStream = conn.getOutputStream();// 注意编码格式outputStream.write(param.getBytes("UTF-8"));outputStream.close();}}if (ObjectUtil.isNotEmpty(headers)) {for (String s : headers.keySet()) {conn.setRequestProperty(s, headers.get(s));}}conn.setRequestProperty("Cookie", cookieStr);// 设置证书忽略相关操作conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String s, SSLSession sslSession) {return true;}});conn.connect();int responseCode = conn.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {InputStream is = conn.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));String ret = "";//输出响应信息while ((ret = br.readLine()) != null) {if (ret != null && !ret.trim().equals("")) {result.append(new String(ret.getBytes("utf-8"), "utf-8"));}}List<String> cookies = conn.getHeaderFields().get("Set-Cookie");//这里返回了连接的cookie信息if (cookies != null) {for (String cookie : cookies) {if (cookie.contains(SyncInfoConfig.COOKIE_NAME)) {// 找到目标CookieString sidCookie = cookie.split(";\\s*")[0];vo.setCookieInfo(sidCookie);break;}}}conn.disconnect();br.close();}} catch (NoSuchAlgorithmException | KeyManagementException | MalformedURLException e) {e.printStackTrace();} catch (IOException ioException) {ioException.printStackTrace();}if (ObjectUtil.isNotEmpty(result)) {vo.setResultStr(result.toString());}return vo;}

http://www.ppmy.cn/news/1270916.html

相关文章

spring面试:二、bean的生命周期和循环引入问题(三级缓存、@Lazy)

bean的生命周期 Spring容器在进行实例化时&#xff0c;会将xml配置的的信息封装成一个BeanDefinition对象&#xff0c;Spring根据BeanDefinition来创建Bean对象&#xff0c;里面有很多的属性用来描述Bean。 其中比较重要的是&#xff1a; beanClassName&#xff1a;bean 的类…

安装鸿蒙开发者工具DevEco Studio

1.进入官网下载工具 https://developer.harmonyos.com/cn/develop/deveco-studio/ 选择您电脑对应的系统下载即可 2.安装 很简单直接点击“next”,此处不做赘述 3.配置环境 安装完成后&#xff0c;打开DevEco Studio 会提示配置环境。安装node.js和ohpm 如果不小心关了&a…

代码随想录算法训练营第二十六天(回溯算法篇)|39. 组合总和,40. 组合总和Ⅱ

39. 组合总和 题目链接&#xff1a;39. 组合总和 - 力扣&#xff08;LeetCode&#xff09; 题目内容&#xff1a;给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target &#xff0c;找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 &#xff0…

[蓝桥杯刷题]合并区间、最长不连续子序列、最长不重复数组长度

前言 ⭐Hello!这里是欧_aita的博客。 ⭐今日语录: 成功的关键在于对目标的持久追求。 ⭐个人主页&#xff1a;欧_aita ψ(._. )>⭐个人专栏&#xff1a; 数据结构与算法 数据库 文章目录 前言合并区间问题&#x1f4d5;现实应用大致思路代码实现代码讲解 最长不连续子序列&a…

vue2.0使用vue-pdf(简单版本)

1.引入vue-pdf&#xff08;vue-pdf版本&#xff1a;4.3.0&#xff0c;vue版本&#xff1a;2.6.14&#xff09; npm install --save vue-pdf2.引入本地文件&#xff08;放public文件夹下用于测试。后期用接口返回的地址&#xff09; 111.pdf&#xff1a;自己随意生成的一个 3…

美容店预约小程序搭建指南

随着互联网的发展&#xff0c;越来越多的传统行业开始尝试将业务与互联网相结合&#xff0c;以提供更加便捷、高效的服务。美容行业也不例外。本文将通过使用第三方制作平台&#xff0c;如乔拓云网&#xff0c;指导您如何搭建一个美观实用的美容店预约小程序&#xff0c;帮助您…

用提问的方式来学习:冯·诺伊曼体系结构与操作系统OS

学习冯诺伊曼体系结构之前&#xff0c;我们要本着两个问题来学习&#xff1a; 什么是冯诺伊曼体系结构&#xff1f;为什么要有冯诺伊曼体系结构&#xff1f; 一、冯诺伊曼体系结构 1. 什么是冯诺伊曼体系结构&#xff1f; 那我们就先来回答一下什么是冯诺伊曼体系结构&#x…

(SpringBoot)第十一章:SpringBoot 统一功能处理(AOP实战)

文章目录 一:用户登录权限验证(1)传统用户登录验证(2)使用原生Spring AOP进行用户登录验证(3)Spring 拦截器A:自定义拦截器B:拦截器实现原理①:概述②:源码分析(4)补充:统一访问前缀的添加二:统一异常处理三:统一数据返回格式Spring AOP使Spring Boot统一功能处…