100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 模拟https类型的get post请求时 碰到证书不信任 无法正常获取返回内容的异常

模拟https类型的get post请求时 碰到证书不信任 无法正常获取返回内容的异常

时间:2023-09-30 00:12:56

相关推荐

模拟https类型的get post请求时 碰到证书不信任 无法正常获取返回内容的异常

解决方案,借助X509TrustManager,再创建httpClient的时候设置信任所有证书,

自己封装的创建closeableHttpClient

public static CloseableHttpClient createHttpsClient() throws Exception {//证书信任管理者X509TrustManager x509mgr = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] xcs, String string) {}@Overridepublic void checkServerTrusted(X509Certificate[] xcs, String string) {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};//获取一个SSLContext实例SSLContext sslContext = SSLContext.getInstance("TLS");//初始化SSLContext实例sslContext.init(null, new TrustManager[]{x509mgr}, new java.security.SecureRandom());//构建一个SSLConnectionSocket工厂,设置为信任所有证书SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);//返回CloseableHttpClient对象return HttpClients.custom().setSSLSocketFactory(sslsf).build();}

用法示例

/*** 发送Post请求* @param url url* @param params json,发送的内容* @param headers headers,发送头* @return true or false*/public static JSONObject post(String url, String params, String headers){CloseableHttpClient closeableHttpClient = null;JSONObject result = new JSONObject();//建立一个连接try {closeableHttpClient = createHttpsClient();//创建一个HttpPostHttpPost httpPost = new HttpPost(url);//设置发送的内容httpPost.setEntity(new StringEntity(params));//设置头信息JSONObject jsonObject = JSONObject.parseObject(headers);Set<String> keys = jsonObject.keySet();for (String key : keys){httpPost.setHeader(key,jsonObject.getString(key));}//发送HttpResponse httpResponse = closeableHttpClient.execute(httpPost);int returnCode = httpResponse.getStatusLine().getStatusCode();if (returnCode == HttpStatus.SC_OK) {InputStream is = httpResponse.getEntity().getContent();BufferedReader in = new BufferedReader(new InputStreamReader(is));StringBuffer buffer = new StringBuffer();String line = "";while ((line = in.readLine()) != null) {buffer.append(line);}result.put("code","200");result.put("result",JSONObject.parseObject(buffer.toString()));return result;} else {result.put("code","404");result.put("result","no result");return result;}} catch (Exception e) {e.printStackTrace();result.put("code","404");result.put("result","no result");return result;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。