public static String request(String url, Map params) { BufferedReader in = null; CloseableHttpResponse response = null; CloseableHttpClient client = null; try { SSLContext sc = SSLContext.getInstance("SSLv3"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; sc.init(null, new TrustManager[]{trustManager}, null); // 设置协议http和https对应的处理socket链接工厂的对象 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sc)) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); //创建自定义的httpclient对象 client = HttpClients.custom().setConnectionManager(connManager).build(); // 实例化HTTP方法 HttpPost request = new HttpPost(); request.setURI(new URI(url)); //设置参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) { String name = (String) iter.next(); String value = String.valueOf(params.get(name)); nvps.add(new BasicNameValuePair(name, value)); //System.out.println(name +"-"+value); } request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 200) { //请求成功 in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent(), "utf-8")); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); return sb.toString(); } else { // System.out.println("状态码:" + code); return "请求失败"; } } catch (Exception e) { e.printStackTrace(); return "请求失败"; }finally { try { if(response!=null){ response.close(); } if(client!=null){ client.close(); } } catch (IOException e) { e.printStackTrace(); } } }
httpclient 支持http ,https
最新推荐文章于 2022-06-18 17:14:01 发布