2012-03-07 89 views
0

我對android應用程序開發非常陌生。我正在開發一個演示項目,我試圖將我的android應用程序用作在C#.net上創建的WCF REST服務的客戶端。該服務已經託管在互聯網服務器中,並且正在正常工作,因爲我在其他.Net Web應用程序(如客戶端)中使用了相同的服務。 但是,當我試圖從我的android應用程序訪問相同的REST服務(返回一個JSON對象)時,它拋出以下異常。如何從Android應用程序中使用HTTPS休息服務

「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(); 
     } 

我是否需要以忽略SSL證書錯誤,請確認創建我自己的TrustManager的SSLContext。如果是,請提供代碼示例。

回答

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); 
+0

試過這個..錯誤依然存在。添加更多的信息.​​.我試圖從模擬器訪問服務。目前甚至從仿真器的瀏覽器無法訪問任何「https」開頭的網站,「HTTP」 S工作正常。我是否需要爲此更改任何模擬器設置?請幫助..有 – 2012-03-09 12:25:21

+0

同樣的問題,你解決了嗎? – user1159819 2012-10-05 20:10:22

2

你提到的代碼將在真實的設備上工作。您提出的問題是由您的PC中阻止443端口的防火牆引起的。

嘗試禁用防火牆並在模擬器中嘗試您的應用程序。我相信它會起作用。

相關問題