`
lumingming1987
  • 浏览: 116618 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

HttpClientUtils获取responseCode(含https)

 
阅读更多

使用apache的httpclient支持SSL(https)安全协议

1.调用方法

int code = HttpClientUtils.postForReturnCode(url.toString());

 2.HttpClientUtils代码

package com.sf.integration.sso.access;

import java.net.URL;
import java.security.Security;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class HttpClientUtils {
	
	private static final Logger log = Logger.getLogger(HttpClientUtils.class);

	public static String get(String url) {
		return send("get", url);
	}

	public static String post(String url) {
		return send("post", url);
	}
	
	//返回code的方法
	public static int postForReturnCode(String url) {
		return sendForReturnCode("post", url);
	}
	
	public static String send(String method, String url) {
		String body = "error";
		HttpMethod httpMethod = null;
		if (method.equalsIgnoreCase("post")) {
			httpMethod = new PostMethod(url); // 输入网址
		} else {
			httpMethod = new GetMethod(url); // 输入网址
		}
		HttpClient client = new HttpClient();
		try {
			if (url.startsWith("https:")) {
				supportSSL(url, client);
			}
			client.getParams().setContentCharset("UTF-8"); // 处理中午字符串
			client.executeMethod(httpMethod);
			body = httpMethod.getResponseBodyAsString();
			int code = httpMethod.getStatusCode();
			System.out.println(code);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return body;
	}
	
	public static int sendForReturnCode(String method, String url) {
		int code = 403;
		HttpMethod httpMethod = null;
		if (method.equalsIgnoreCase("post")) {
			httpMethod = new PostMethod(url); // 输入网址
		} else {
			httpMethod = new GetMethod(url); // 输入网址
		}
		HttpClient client = new HttpClient();
		try {
			if (url.startsWith("https:")) {
				supportSSL(url, client);
			}
			client.getParams().setContentCharset("UTF-8"); // 处理中午字符串
			client.executeMethod(httpMethod);
			code = httpMethod.getStatusCode();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return code;
	}
	
	private static void supportSSL(String url, HttpClient client) {
        if(StringUtils.isBlank(url)) {
            return;
        }
        String siteUrl = StringUtils.lowerCase(url);
        if (!(siteUrl.startsWith("https"))) {
            return;
        }
       
        try {
           setSSLProtocol(siteUrl, client);
        } catch (Exception e) {
            log.error("setProtocol error ", e);
        }
        Security.setProperty( "ssl.SocketFactory.provider","com.tool.util.DummySSLSocketFactory");
    }
	
	private static void setSSLProtocol(String strUrl, HttpClient client) throws Exception {	       
        URL url = new URL(strUrl);
        String host = url.getHost();
        int port = url.getPort();

        if (port <= 0) {
            port = 443;
        }
        ProtocolSocketFactory factory = new DummySSLSocketFactory();
        Protocol authhttps = new Protocol("https", factory, port);
        Protocol.registerProtocol("https", authhttps);
        client.getHostConfiguration().setHost(host, port, authhttps);
    }
}

 3.DummySSLSocketFactory验证代码

package com.sf.integration.sso.access;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;


public class DummySSLSocketFactory implements SecureProtocolSocketFactory {

	private SSLContext sslcontext = null;
	   
    private SSLContext createSSLContext() {
        SSLContext sslcontext=null;
        try {
            sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return sslcontext;
    }
   
    private SSLContext getSSLContext() {
        if (this.sslcontext == null) {
            this.sslcontext = createSSLContext();
        }
        return this.sslcontext;
    }
   
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(
                socket,
                host,
                port,
                autoClose
            );
    }

    public Socket createSocket(String host, int port) throws IOException,
            UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(
                host,
                port
            );
    }
   
   
    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
    }

    public Socket createSocket(String host, int port, InetAddress localAddress,
            int localPort, HttpConnectionParams params) throws IOException,
            UnknownHostException, ConnectTimeoutException {
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }
        int timeout = params.getConnectionTimeout();
        SocketFactory socketfactory = getSSLContext().getSocketFactory();
        if (timeout == 0) {
            return socketfactory.createSocket(host, port, localAddress, localPort);
        } else {
            Socket socket = socketfactory.createSocket();
            SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
            SocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
            return socket;
        }
    }
   
    private static class TrustAnyTrustManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

}

 

分享到:
评论

相关推荐

    HttpClient 卡死 response 为 null - 帐前卒 - CSDN1

    在使用Apache HttpClient库进行HTTP请求时,可能会遇到`HttpClient`返回`response`为`null`的问题,这通常意味着请求没有成功地完成或者某些资源没有被正确处理。在本篇文章中,我们将深入探讨这个问题的原因和解决...

    HttpClient获取OAuth2.0中的code

    通过httpclient post去获取,response返回码是302,返回的code放在header的Location中。 请求的时候client_id,response_type,redirect_uri,state拼接在url后面,account和password放在body表单(x-...

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    HttpResponse response = httpClient.execute(request); ``` 现在,我们转向主题——忽略SSL验证。在生产环境中,SSL验证是必须的,以确保数据传输的安全性。但在开发或测试环境中,我们可能需要绕过这一环节。...

    JAVA利用HttpClient进行HTTPS接口调用

    3. 使用HttpClientUtil创建的HttpClient实例执行请求,如`CloseableHttpResponse response = httpClient.execute(request);` 4. 检查响应状态码,例如,200表示成功,其他代码可能表示错误。 5. 读取响应内容,如果...

    通过HTTPClient获取网络资源

    本篇文章将深入探讨如何使用`HttpClient`来获取网络资源,以及处理返回的XML数据。 首先,我们需要了解`HttpClient`的基本用法。在Java中,创建一个`HttpClient`实例是获取网络资源的第一步。`HttpClient`提供了...

    HttpClient以及获取页面内容应用

    15. 直接获取服务器发送的response code和 headers。 16. 设置连接超时的能力。 17. 实验性的支持http1.1 response caching。 18. 源代码基于Apache License 可免费获取。 1.3版本 org.apache....

    java httpclient工具

    HttpClient提供了丰富的功能,允许用户执行各种HTTP操作,如GET、POST、PUT等,并且支持HTTPS、Cookie管理、重试机制、连接池管理和多线程处理等。在本文中,我们将深入探讨Java HttpClient工具的使用方法、核心概念...

    httpclient httpclient.jar

    这个库广泛用于从Web服务器获取数据、发送请求、处理响应等任务,尤其在爬虫、API交互、自动化测试等领域有着广泛的应用。在本文中,我们将深入探讨HttpClient的核心概念、使用方法以及如何通过`httpclient.jar`进行...

    httpClient和htmlparse获取网页数据使用jar

    3. 发起请求并获取响应:`CloseableHttpResponse response = httpClient.execute(httpGet);` 4. 处理响应内容:`HttpEntity entity = response.getEntity();` 5. 关闭资源:`response.close();` HtmlParser是一个...

    使用HttpClient发送POST请求,并获取响应内容(附详细步骤).txt

    ### 使用HttpClient发送POST请求,并获取响应内容 #### 一、简介 在现代软件开发中,尤其是在Web应用领域,客户端与服务器之间的通信是非常重要的环节。Java作为一种广泛应用的编程语言,提供了多种方式来实现这一...

    使用HttpClient获取网页html源代码.zip

    设置完请求后,我们通过HttpClient执行请求并获取HttpResponse: ```java HttpResponse response = httpClient.execute(httpGet); ``` 在响应对象中,我们可以找到HttpEntity,它包含了服务器返回的数据。使用...

    Client-https-server.rar_httpclient服务器_https_https client_https c

    CloseableHttpResponse response = httpclient.execute(target, request); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System....

    struts2获取response的方法

    以下是对"struts2获取response的方法"的详细说明。 1. **ActionSupport类的实现** Struts2中的Action类通常会继承自`org.apache.struts2.interceptor.StrutsPrepareAndExecuteInterceptor`或`...

    Android使用HttpClient和HttpsUrlConnection两种方式访问https网站

    HttpResponse response = httpClient.execute(httpGet); ``` 这里的`EasySSLSocketFactory`是一个自定义的SSL套接字工厂,它允许跳过证书验证。 #### 1.2 配置HttpClient验证证书 为了确保安全性,通常需要验证...

    httpclient获取目标网站内容,get、post方式(可运行)

    本项目提供了可运行的示例,展示了如何使用HttpClient来获取目标网站内容。 首先,`pom.xml`是Maven项目的配置文件,它包含了项目所依赖的库,如Apache HttpClient库。在`pom.xml`中,你需要确保引入了正确的...

    httpClient调用远程接口获取数据到本地文件夹

    在这个例子中,我们使用HttpClient来调用远程接口,从电信公司的网站获取可用手机号码的数据,并将其存储到本地文件系统。以下是对这个过程的详细解释: 1. **HttpClient的引入与配置**: 首先,我们需要在项目中...

    Spring MVC 中几种获取request和response的方式

    Spring MVC 中几种获取request和response的方式,讲解详细实用!

    HttpClient发起HTTPs请求.rar

    在这个"HttpClient发起HTTPs请求.rar"压缩包中,我们主要关注的是如何利用HttpClient处理HTTPS协议的GET和POST请求,以及如何处理返回的JSON数据。这里,我们将详细讨论相关知识点。 首先,HTTPS是一种基于SSL/TLS...

    Struts2通过使用ActionContext类获取request和response对象

    在Struts2中,ActionContext不仅仅是获取request和response的工具,它还包含了其他有用的上下文信息,如session、application等。例如,你可以通过ActionContext获取session中的数据: ```java Map, Object&gt; ...

    Android HttpURLConnection.getResponseCode()错误解决方法

    正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是IOException错误,responseCode = -1。一直想不明白,同一个程序我调用了两次,结果有一个链接一直OK,另一个却一直报这个错误。后来发现两个...

Global site tag (gtag.js) - Google Analytics