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

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

HttpsURLConnection报错方法示例(这是报错示例):

			// 发起HTTPS POST请求
            URL url = new URL("https://example.com/api/resource");
            connection = (HttpsURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.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里面):

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.4.6</version>
</dependency>

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, String
            param, 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() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            }, new SecureRandom());
            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            // GET/POST
            conn.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() {
                @Override
                public 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)) {
                            // 找到目标Cookie
                            String 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;
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用HttpClient发送Post请求携带cookie的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List; public class HttpClientUtil { public static void main(String[] args) throws Exception { // 创建HttpClient实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建CookieStore实例 CookieStore cookieStore = new BasicCookieStore(); // 创建HttpPost实例 HttpPost httpPost = new HttpPost("http://example.com/login"); // 设置请求参数 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); // 设置请求httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置请求参数 List<BasicNameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("username", "example")); parameters.add(new BasicNameValuePair("password", "password")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); httpPost.setEntity(formEntity); // 执行HttpPost请求 HttpResponse httpResponse = httpClient.execute(httpPost); // 获取响应实体 HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } // 获取Cookie List<Cookie> cookies = cookieStore.getCookies(); // 创建HttpPost实例 httpPost = new HttpPost("http://example.com/data"); // 设置请求参数 requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); // 设置请求httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Accept", "application/json"); // 设置请求参数 String requestBody = "{\"key\":\"value\"}"; httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); // 设置Cookie httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); // 执行HttpPost请求 httpResponse = httpClient.execute(httpPost); // 获取响应实体 httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值