如何从Android应用程序中使用HTTPS休息服务

时间:2012-03-07 12:11:56

标签: android rest ssl https certificate

我是Android应用程序开发的新手。我正在开发一个演示项目,我试图将我的android应用程序用作在C#.net上创建的WCF REST服务的客户端。该服务已经托管在互联网服务器中,并且工作正常,因为我在其他.Net Web应用程序(作为客户端)中使用相同的服务。 但是,当我尝试从我的Android应用程序访问相同的REST服务(返回一个JSON对象)时,它会抛出异常。

“java.io.IOException:SSL握手失败:SSL库失败,通常是协议错误 错误:140770FC:SSL例程:SSL23_GET_SERVER_HELLO:未知协议(外部/ openssl / ssl / s23_clnt.c:585 0xaf586674:0x00000000)“

以下是我用来连接服务的代码。

final String url = "https://mywebsite.com/service/myservice.svc/userid/" + usrid + "/" + password + "/authenticate";

        Uri uri = Uri.parse(url);
        HttpClient httpclient = new DefaultHttpClient();
        HttpHost host = new HttpHost(uri.getHost(), 443, uri.getScheme());
        HttpPost httppost = new HttpPost(uri.getPath());
        try {
            HttpResponse response = httpclient.execute(host, httppost);  // Throwing exception on this line
               HttpEntity entity = response.getEntity();
            if (entity != null) { 
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                JSONArray nameArray=json.names();
                JSONArray valArray=json.toJSONArray(nameArray);
                for(int i=0;i<valArray.length();i++)
                {
                    nameArray.getString(i);
                } 
                instream.close();
            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

我是否需要使用自己的TrustManager创建SSLContext以忽略SSL证书错误,请确认。如果是,您能否提供代码示例。

2 个答案:

答案 0 :(得分:2)

您提到的代码将在真实设备中使用。您提出的问题是由PC中阻止443端口的防火墙引起的。

尝试禁用防火墙并在模拟器中试用您的应用程序。我相信它会奏效。

答案 1 :(得分:0)

是..您需要使用自己的TrustManager创建SSLContext,以忽略SSL证书错误。

<强> EasySSLSocketFactory.java

 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.Socket;
 import java.net.UnknownHostException;

 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.TrustManager;

 import org.apache.http.conn.ConnectTimeoutException;
 import org.apache.http.conn.scheme.LayeredSocketFactory;
 import org.apache.http.conn.scheme.SocketFactory;
 import org.apache.http.params.HttpConnectionParams;
 import org.apache.http.params.HttpParams;

public class EasySSLSocketFactory implements SocketFactory, 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, java.lang.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, java.lang.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();
}

}

<强> EasyX509TrustManager.java

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

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(X509Certificate[],String authType)
 */
public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    standardTrustManager.checkClientTrusted(certificates, authType);
}

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(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();
}

}

现在拨打Https服务:

 String urlToSendRequest = "https://example.com";
            String targetDomain = "example.com";

    DefaultHttpClient httpClient = new DefaultHttpClient();

     SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http",    PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

HttpParams params = new BasicHttpParams();
params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
                params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
            params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");
    ClientConnectionManager cm =  new ThreadSafeClientConnManager(params, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, params);

    HttpHost targetHost = new HttpHost(targetDomain, 443, "https");
            // Using POST here
    HttpPost httpPost = new HttpPost(urlToSendRequest);
            // Make sure the server knows what kind of a response we will accept

    // Also be sure to tell the server what kind of content we are sending
    httpPost.addHeader("Content-Type", "application/xml"); 

    StringEntity entity = new StringEntity("<input>test</input>", "UTF-8");
            entity.setContentType("application/xml");
            httpPost.setEntity(entity);


CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            //set the user credentials for our site "example.com"
credentialsProvider.setCredentials(new AuthScope(targetDomain, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("", ""));
            HttpContext context = new BasicHttpContext();
context.setAttribute("http.auth.credentials-provider", credentialsProvider);

            // execute is a blocking call, it's best to call this code in a
            // thread separate from the ui's
HttpResponse response = httpClient.execute(httpPost, context);