2013-05-12 62 views
13

我想做一個HTTPS發佈方法,從我的android應用程序發送一些數據到我的網站。如何從Android執行HTTPS POST?

我首先使用了HttpURLConnection,並且它與我的HTTP URL一起工作正常。我的生產網站使用HTTPS,我想用HttpsURLConnection發送相同的POST。有人可以幫助我正確使用課程嗎?

我發現在一些this link來源:

KeyStore keyStore = ...;  
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");  
tmf.init(keyStore); 

SSLContext context = SSLContext.getInstance("TLS"); 
context.init(null, tmf.getTrustManagers(), null); 

URL url = new URL("https://www.example.com/"); 
HttpsURLConnection urlConnection = (HttpsURLConnection) 
url.openConnection(); 
urlConnection.setSSLSocketFactory(context.getSocketFactory()); 
InputStream in = urlConnection.getInputStream(); 

應該是什麼的KeyStore keyStore = ...;價值?

我嘗試使用相同的HttpURLConnection發送數據,但我看到一些POST數據被遺漏或出錯。我試過this question的方法。我粘貼下面

String urlParameters="dateTime=" + URLEncoder.encode(dateTime,"UTF-8")+ 
    "&mobileNum="+URLEncoder.encode(mobileNum,"UTF-8"); 

URL url = new URL(myurl); 
HttpsURLConnection conn; 
conn=(HttpsURLConnection)url.openConnection(); 

// Create the SSL connection 
SSLContext sc; 
sc = SSLContext.getInstance("TLS"); 
sc.init(null, null, new java.security.SecureRandom()); 
conn.setSSLSocketFactory(sc.getSocketFactory()); 
conn.setConnectTimeout(HTTP_CONNECT_TIME_OUT); 
conn.setReadTimeout(HTTP_READ_TIME_OUT); 

//set the output to true, indicating you are outputting(uploading) POST data 
conn.setDoOutput(true); 
//once you set the output to true, you don't really need to set the request method to post, but I'm doing it anyway 
conn.setRequestMethod("POST"); 
conn.setFixedLengthStreamingMode(urlParameters.getBytes().length); 
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

PrintWriter out = new PrintWriter(conn.getOutputStream()); 
out.print(urlParameters); 
out.close(); 

InputStream is = conn.getInputStream(); 
BufferedReader in = new BufferedReader(new InputStreamReader(is)); 
String inputLine; 
while ((inputLine = in.readLine()) != null) { 
    response += inputLine;    
}     

我得到的錯誤我的代碼如下:

05-12 19:36:10.758: W/System.err(1123): java.io.FileNotFoundException: https://www.myurl.com/fms/test 
05-12 19:36:10.758: W/System.err(1123):  at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177) 
05-12 19:36:10.758: W/System.err(1123):  at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:270) 
05-12 19:36:10.758: W/System.err(1123):  at .httpRequest(SMSToDBService.java:490) 
05-12 19:36:10.758: W/System.err(1123):  at com..access$0(SMSToDBService.java:424) 
05-12 19:36:10.758: W/System.err(1123):  at com.$ChildThread$1.handleMessage(SMSToDBService.java:182) 
05-12 19:36:10.758: W/System.err(1123):  at android.os.Handler.dispatchMessage(Handler.java:99) 
05-12 19:36:10.758: W/System.err(1123):  at android.os.Looper.loop(Looper.java:156) 
05-12 19:36:10.758: W/System.err(1123):  at com.$ChildThread.run(SMSToDBService.java:303) 
+0

份額日誌,你看到 – tbkn23 2013-05-12 05:50:15

+0

與谷歌上面的示例代碼中的錯誤,我不知道在密鑰庫密鑰庫放什麼= ...; – Dino 2013-05-12 06:56:23

+0

httpRequest IOException:java.io.FileNotFoundException:這個錯誤發生在某些POST方法中,我使用HttpURLConnection和https URL – Dino 2013-05-12 07:08:11

回答

17

您可以使用在Android設備上,這是蠻好的任何公共網絡中定義的默認的CA 。

如果您有自簽名證書,您可以接受所有證書(風險較高,面向中間人攻​​擊)或創建自己的TrustManagerFactory,這有點超出此範圍。

下面是一些代碼使用默認的CA爲HTTPS POST電話:

private InputStream getInputStream(String urlStr, String user, String password) throws IOException 
{ 
    URL url = new URL(urlStr); 
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 

    // Create the SSL connection 
    SSLContext sc; 
    sc = SSLContext.getInstance("TLS"); 
    sc.init(null, null, new java.security.SecureRandom()); 
    conn.setSSLSocketFactory(sc.getSocketFactory()); 

    // Use this if you need SSL authentication 
    String userpass = user + ":" + password; 
    String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT); 
    conn.setRequestProperty("Authorization", basicAuth); 

    // set Timeout and method 
    conn.setReadTimeout(7000); 
    conn.setConnectTimeout(7000); 
    conn.setRequestMethod("POST"); 
    conn.setDoInput(true); 

    // Add any data you wish to post here 

    conn.connect(); 
    return conn.getInputStream(); 
} 

要讀取響應:

 String result = new String(); 
     InputStream is = getInputStream(urlStr, user, password); 
     BufferedReader in = new BufferedReader(new InputStreamReader(is)); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) { 
      result += inputLine;    
     }  
+0

IOException:java.io.IOException:此消息即將到達的流的意外結束 – Dino 2013-05-12 13:14:55

+0

InputStream inStream = conn.getInputStream(); response = inStream.toString(); – Dino 2013-05-12 13:24:46

+0

我從來沒有嘗試用'toString()'讀取'InputStream' ...添加了我用於讀取流的代碼 – tbkn23 2013-05-12 13:51:51

4

你可以看看這個問題,我問了幾天前:

Change HTTP post request to HTTPS post request:

我提供了有一個解決方案ŧ帽子爲我工作,基本上接受任何自簽名證書。正如這裏所說的,這個解決方案不被推薦,因爲它不安全,並且面臨中間人攻擊。

下面是代碼:

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

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

DefaultHttpClient client = new DefaultHttpClient(); 

我將其替換爲:

HttpClient client = getNewHttpClient(); 
+0

已棄用HttpClient – 2017-01-20 05:41:16

+0

MySSLSocketFactory? – Shankar 2017-09-10 07:08:11

3

下面是一個Android HttpsUrlConnection POST solution完整的證書釘扎,超時服務器端代碼和配置。

變量params應該採用username = demo & password = abc123 &。

@Override 
public String sendHttpRequest(String params) { 
    String result = ""; 
    try { 
     URL url = new URL(AUTHENTICATION_SERVER_ADDRESS); 
     HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 
     connection.setSSLSocketFactory(KeyPinStore.getInstance().getContext().getSocketFactory()); // Tell the URLConnection to use a SocketFactory from our SSLContext 
     connection.setRequestMethod("POST"); 
     connection.setDoOutput(true); 
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     connection.setConnectTimeout(10000); 
     connection.setReadTimeout(10000); 
     PrintWriter out = new PrintWriter(connection.getOutputStream()); 
     out.println(params); 
     out.close(); 
     BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()), 8192); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) { 
      result = result.concat(inputLine); 
     } 
     in.close(); 
     //} catch (IOException e) { 
    } catch (IOException | KeyStoreException | CertificateException | KeyManagementException | NoSuchAlgorithmException e) { 
     result = e.toString(); 
     e.printStackTrace(); 
    } 
    return result; 
} 
+0

很好。它適用於我的棒棒糖5.0。謝謝。 什麼是KeyPinStore? – ashishdhiman2007 2017-05-30 09:39:41