How to do an HTTPS POST from Android?

后端 未结 3 1042
日久生厌
日久生厌 2020-11-29 04:07

I want to do a HTTPS post method to send some data from my android app to my website.

I used HttpURLConnection first and it\'s working fine with my HTT

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 04:34

    You can use the default CAs that are defined in the android device, which is just fine for any public web.

    If you have a self-signed certificate, you can either accept all certificates (risky, open to man-in-the-middle attacks) or create your own TrustManagerFactory, which is a bit out of this scope.

    Here's some code to use the default CAs for a https POST call:

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

    To read the response:

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

提交回复
热议问题