2012-03-07 3 views
0

나는 안드로이드 응용 프로그램 개발에 매우 ​​익숙하다. 데모 프로젝트에서 일하고 있는데 C# .net에서 만든 WCF REST 서비스의 클라이언트로 안드로이드 응용 프로그램을 사용하려고합니다. 이 서비스는 이미 인터넷 서버에 호스팅되어 있으며 내 .Net 웹 응용 프로그램 (클라이언트)에서 동일한 서비스를 사용하고 있으므로 제대로 작동합니다. 그러나 내 안드로이드 응용 프로그램에서 JSON 객체를 반환하는 동일한 REST 서비스에 액세스하려고 할 때 예외가 발생합니다.안드로이드 응용 프로그램에서 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

예 SSL 인증서 오류를 무시하려면 자체 TrustManager를 사용하여 SSLContext를 만들어야합니다.

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"가 제대로 작동합니다. 이 문제에 대한 에뮬레이터 설정을 변경해야합니까? 제발 도와주세요 .. –

+0

같은 문제가 있으십니까? – user1159819

2

당신이 언급 한 코드 실제 장치에서 작동합니다. 443 포트를 차단하는 PC의 방화벽 때문에 문제가 발생했습니다.

방화벽을 비활성화하고 에뮬레이터에서 응용 프로그램을 사용해보십시오. 나는 그것이 효과가있을 것이라고 믿는다.

관련 문제