我有一个需要通过https请求连接到网络服务的应用
我正在使用EasySSLSocket库来做到这一点
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* This socket factory will create ssl socket that accepts self signed
* certificate
*
* @author olamy
* @version $Id: EasySSLSocketFactory.java 765355 2009-04-15 20:59:07Z evenisse
* $
* @since 1.2.3
*/
public class EasySSLSocketFactory implements LayeredSocketFactory {
private SSLContext sslcontext = null;
private static SSLContext createEasySSLContext() throws IOException {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { new EasyX509TrustManager(
null) }, null);
return context;
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
private SSLContext getSSLContext() throws IOException {
if (this.sslcontext == null) {
this.sslcontext = createEasySSLContext();
}
return this.sslcontext;
}
/**
* @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
* String, int, java.net.InetAddress, int,
* org.apache.http.params.HttpParams)
*/
public Socket connectSocket(Socket sock, String host, int port,
InetAddress localAddress, int localPort, HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
if ((localAddress != null) || (localPort > 0)) {
// we need to bind explicitly
if (localPort < 0) {
localPort = 0; // indicates "any"
}
InetSocketAddress isa = new InetSocketAddress(localAddress,
localPort);
sslsock.bind(isa);
}
sslsock.connect(remoteAddress, connTimeout);
sslsock.setSoTimeout(soTimeout);
return sslsock;
}
/**
* @see org.apache.http.conn.scheme.SocketFactory#createSocket()
*/
public Socket createSocket() throws IOException {
return getSSLContext().getSocketFactory().createSocket();
}
/**
* @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket)
*/
public boolean isSecure(Socket socket) throws IllegalArgumentException {
return true;
}
/**
* @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
* String, int, boolean)
*/
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
}
// -------------------------------------------------------------------
// javadoc in org.apache.http.conn.scheme.SocketFactory says :
// Both Object.equals() and Object.hashCode() must be overridden
// for the correct operation of some connection managers
// -------------------------------------------------------------------
public boolean equals(Object obj) {
return ((obj != null) && obj.getClass().equals(
EasySSLSocketFactory.class));
}
public int hashCode() {
return EasySSLSocketFactory.class.hashCode();
}
}
public class EasyX509TrustManager
implements X509TrustManager
{
private X509TrustManager standardTrustManager = null;
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager( KeyStore keystore )
throws NoSuchAlgorithmException, KeyStoreException
{
super();
TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
factory.init( keystore );
TrustManager[] trustmanagers = factory.getTrustManagers();
if ( trustmanagers.length == 0 )
{
throw new NoSuchAlgorithmException( "no trust manager found" );
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
* @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[],String authType)
*/
public void checkClientTrusted( X509Certificate[] certificates, String authType )
throws CertificateException
{
standardTrustManager.checkClientTrusted( certificates, authType );
}
/**
* @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[],String authType)
*/
public void checkServerTrusted( X509Certificate[] certificates, String authType )
throws CertificateException
{
if ( ( certificates != null ) && ( certificates.length == 1 ) )
{
certificates[0].checkValidity();
}
else
{
standardTrustManager.checkServerTrusted( certificates, authType );
}
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
public X509Certificate[] getAcceptedIssuers()
{
return this.standardTrustManager.getAcceptedIssuers();
}
}
以下是我连接套接字的方法
private static HttpClient getHttpClient() {
if(manager == null) {
// sets up parameters
clientParams = new BasicHttpParams();
HttpProtocolParams.setVersion(clientParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(clientParams, HTTP.UTF_8);
clientParams.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
// registers schemes for both http and https
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme(HTTP_PREFIX, PlainSocketFactory.getSocketFactory(), HTTP_PORT));
registry.register(new Scheme(HTTPS_PREFIX, new EasySSLSocketFactory(), HTTPS_PORT));
manager = new ThreadSafeClientConnManager(clientParams, registry);
}
return new DefaultHttpClient(manager, clientParams);
}
为什么在某些设备上我收到此错误:
12-12 08:59:01.565 E/HTTPUtils(23906): javax.net.ssl.SSLException: Read error: ssl=0x5903ef90: I/O error during system call, Connection reset by peer
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_read(Native Method)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:651)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
12-12 08:59:01.565 E/HTTPUtils(23906): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
答案 0 :(得分:0)
在移动世界中,通常原因只是客户端应用程序运行的蜂窝网络。如果您的请求失败,请准备好重试。