如何在Android上进行HTTPS POST请求?

18

我希望通过HTTPS POST方法从我的Android应用程序发送一些数据到我的网站。

我先使用了HttpURLConnection,并且在我的HTTP URL上运行良好。我的生产网站在HTTPS上,我想使用HttpsURLConnection发送相同的POST。有人能帮我正确使用这个类吗?

我在这个链接上找到了一些源代码:

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数据丢失或出错。

我已经尝试了这个问题中的方法。我将我的代码粘贴在下面。

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)

请分享您看到的日志和错误。 - tbkn23
使用谷歌提供的示例代码,我不知道在 KeyStore keyStore = ...; 中应该放什么。 - DJM
httpRequest IOException: java.io.FileNotFoundException: 这个错误发生在一些POST方法中,我正在使用带有https URL的HttpURLConnection。 - DJM
1
如果我使用HttpsURLConnection,我会看到相同的错误.. 我没有执行以下任何代码 KeyStore keyStore = ...; TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(keyStore);SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); - DJM
3个回答

20

您可以使用Android设备中定义的默认CA证书,这对于任何公共网络都很好。

如果您有自签名证书,您可以选择接受所有证书(存在风险,易受中间人攻击),或者创建自己的TrustManagerFactory,但这超出了本范围的讨论。

以下是一些代码,可用于进行https POST调用的默认CA证书:

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

IOException:java.io.IOException:流意外结束,出现此消息 - DJM
InputStream inStream = conn.getInputStream(); response = inStream.toString();输入流inStream = conn.getInputStream(); 响应 = inStream.toString(); - DJM
我从未尝试使用toString()来读取InputStream… 这是我用来读取流的代码。 - tbkn23
getInputStream() 抛出的 FileNotFoundException 是由于 Web 服务器返回错误 - 通常是 404(文件未找到)引起的。这与打开连接无关,连接已经正常工作。尝试使用 FireBug Firefox 插件调试 Web 服务器。您可以使用 getErrorStream() 读取错误消息。 - tbkn23
如何使用 getErrorStream? - DJM
显示剩余3条评论

5
这里有一个关于Android HttpsUrlConnection POST 解决方案的翻译,包括证书固定、超时服务器端代码和配置。
变量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;
}

非常好。它适用于我的棒棒糖5.0。谢谢。 KeyPinStore是什么? - ashishdhiman2007

4
您可以看一下我几天前提出的这个问题:
将HTTP POST请求更改为HTTPS POST请求:
我在那里提供了一个对我有效的解决方案,它基本上接受任何自签名证书。正如在这里所说的那样,这种解决方案并不安全,容易遭受中间人攻击。
以下是代码:
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();

HttpClient已被弃用。 - Nouman Shah
MySSLSocketFactory? - Shankar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接