2013-05-05 341 views
5

我有這樣的方法:更改HTTP POST請求HTTPS POST請求:

public static String getReportMetadata (String reportId, String sessionId, String url) throws Exception{ 

    Map<String, Object> jsonValues = new HashMap<String, Object>(); 
    jsonValues.put("reportID", reportId); 
    jsonValues.put("sessionID", sessionId); 
    JSONObject json = new JSONObject(jsonValues); 

    DefaultHttpClient client = new DefaultHttpClient(); 

    HttpPost post = new HttpPost(url + GET_REPORT_METADATA_ACTION); 

    AbstractHttpEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF8")); 
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
    post.setEntity(entity);   
    HttpResponse response = client.execute(post); 

    return getContent(response);    
} 

執行,其中,當然我跑使用AsyncTask到從服務器獲取數據的HTTP發佈採購信息。

我的問題: 可能有人請用簡單的方法是什麼我需要執行這個連接類型更改爲安全連接(a.k.a使用HTTPS)的步驟,向我解釋。 只能從android的角度來看(意思是客戶端應用程序)。

更新: 正如建議我試圖改變只有鏈接並添加https而不是http,但它不會返回一個答案。據我瞭解我需要獲得並儲存一個自簽證書,才能連接到服務器端

UPDATE2: 爲我的作品的解決方案:

EasySSLSocketFactory:

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:

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

我加入這個方法:getNewHttpClient()

public static HttpClient getNewHttpClient() { 
    try { 
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
     trustStore.load(null, null); 

     SSLSocketFactory sf = new MySSLSocketFactory(trustStore); 
     sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

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

     ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

     return new DefaultHttpClient(ccm, params); 
    } catch (Exception e) { 
     return new DefaultHttpClient(); 
    } 
} 

最後在我的代碼,每一個地方,我有:

HttpClient client = getNewHttpClient(); 

DefaultHttpClient client = new DefaultHttpClient(); 

我代之以

我現在可以從服務器端接收數據,最後一個問題是:我做的是安全的嗎?或者它接受每個自簽名證書?如果是這種情況,應該做些什麼來改變它?

任何幫助,將不勝感激。

+0

也許javadoc會幫助你:[SchemeRegistry](http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/scheme/SchemeRegistry.html)[SSLSocketFactory](http: //hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/SSLSocketFactory.html) – mleczey 2013-05-05 21:20:41

+1

根據[HTTPClient SSL指南](https p://hc.apache.org/httpclient-legacy/sslguide.html),你唯一需要做的就是在你的URL字符串中加上「https://」。這將爲您提供HTTPS連接,並具有與瀏覽器等效的身份驗證級別(即幾百個CA中的任何一個都可以簽署服務器證書)。 'SchemeRegistry'和'SSLSocketFactory'只有在你想定製SSL處理時纔會起作用,通常是爲了實現SSL固定(即使用更強的真實性約束)。查看Moxie的github是否有良好的(LGPL許可)Android ssl pinner。 – Barend 2013-05-05 21:23:38

+0

@Barend,我試圖只改變鏈接並添加https而不是http,但它不會返回答案。據我所知,我需要獲得並存儲自簽名證書才能連接到服務器端。 – 2013-05-06 09:16:19

回答

5

來自Apache HttpClient SSL guide

通過SSL的安全HTTP通信應該與普通HTTP通信一樣簡單。

所以,你應該簡單地將HTTP改變:// XXXX到HTTPS:// XXXX

編輯:我剛看到@Barend的答案是更完整的

+0

我試圖只改變鏈接並添加https而不是http,但它不會返回一個答案。據我所知,我需要獲得一個自簽名證書才能連接到服務器端。 – 2013-05-06 09:11:47

+0

如果服務器有一個自簽名證書,您需要告訴您的HttpClient接受它。如果你想這樣做,你可以看看這裏http://stackoverflow.com/questions/1217141/self-signed-ssl-acceptance-android – user2340612 2013-05-06 10:44:04

5

首先你需要創建SchemeRegistry對象並使用註冊新方案的SSLSocketFactory的:

SchemeRegistry schemeRegistry = new SchemeRegistry(); 
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); 

然後你就可以使用SchemeRegistry對象創建SingleClientConnManager:

SingleClientConnManager mgr = new SingleClientConnManager(schemeRegistry); 

最後您創建DefaultHttpClient使用SingleClientConnManager:

HttpClient client = new DefaultHttpClient(mgr); 
+0

你想介紹一下這些對象嗎?我應該在每次訪問https web服務之前執行描述的步驟嗎?據我瞭解,我應該從服務器收到證書並將其存儲在設備上,對嗎? – 2013-05-06 09:18:27

+0

@EmilAdz是的,您應該在每次https訪問之前執行這些步驟。 'SchemeRegistry'只是描述HTTPS連接參數的所有'Scheme'對象的一個​​容器,所以你可以爲你的所有調用使用'SchemeRegisty'對象的一個​​實例。但是每次調用您都需要新的'SingleClientConnManager',因爲它一次只能保持一個連接。我認爲存儲SSL證書是由Android自己提供的,所以您不必擔心。 – nemezis 2013-05-06 09:29:06