当前位置 : 主页 > 编程语言 > java >

HttpClient请求

来源:互联网 收集:自由互联 发布时间:2021-06-28
HttpClient请求 /** * 发送https请求 * * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * @return 返回服务器响应的信息 */@Deprecatedpublic String httpsRequ
HttpClient请求
/**
	 * 发送https请求
	 *
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式(GET、POST)
	 * @param outputStr 提交的数据
	 * @return 返回服务器响应的信息
	 */
	@Deprecated
	public String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		String resContent = null;
		DefaultHttpClient httpClient = new DefaultHttpClient ();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(sslContext);
            ssf.setHostnameVerifier(new AllowAllHostnameVerifier ());
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme ("https", ssf, 443));

            HttpPost httpGet = new HttpPost (requestUrl);
            httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");
            httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
            
            httpGet.setEntity(new StringEntity (outputStr, "UTF-8"));

            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = response.getEntity();
                if (httpEntity != null) {
                    resContent = EntityUtils.toString(httpEntity);// 取出应答字符串
                    resContent = new String(resContent.getBytes("ISO-8859-1"), "UTF-8");
                    httpEntity.consumeContent();
                }
            } else {
                httpGet.abort();
            }
        } catch (Exception e) {
            log.error("连接超时:{}", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
		return resContent;
	}
网友评论