如何在Android中执行HTTPS POST请求?

时间:2016-12-28 14:07:47

标签: android https

我使用的是http网址,但现在我需要更改为https。 这是我的代码:

    throws IOException {

    String result = "";
    try {
        String strPost = "";
        for(String key : post.keySet()){
            strPost+= key+"="+post.get(key)+"&";
        }
        strPost = strPost.substring(0,strPost.length()-1);


        URL urlPost = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection)urlPost.openConnection();


        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
        urlConnection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
        urlConnection.setDoOutput(true);

        DataOutputStream dStream = new DataOutputStream(urlConnection.getOutputStream());
        dStream.writeBytes(strPost);
        dStream.flush();
        dStream.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line = "";
        StringBuilder responseOutput = new StringBuilder();
        while((line = br.readLine()) != null ) {
            responseOutput.append(line);
        }
        br.close();

        result = responseOutput.toString();

    }catch (Exception ex){

    }
    return result;
}

我尝试过使用HttpsUrlConnection,但它不起作用。我看了一些关于此的其他问题,但它也没有用。

2 个答案:

答案 0 :(得分:0)

请参阅官方网站Here了解详情。并将HttpURLConnection替换为HttpsURLConnection

答案 1 :(得分:0)

使用以下代码进行https: -

        URL url = new URL(inputURL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(PinnedPublicKeySocketFactory.createSocketFactory());
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("ApiUserName", SoapHeader.VALUE_USERNAME);
        conn.setRequestProperty("ApiPassword", SoapHeader.VALUE_PASSWORD);
        conn.setRequestProperty("ApiKey", SoapHeader.VALUE_AUTH);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(1 * 60 * 1000);


        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(jsonRequest.toString());
        conn.connect();

        if (conn.getResponseCode() == 200) {
            InputStream input = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } 

        out.flush();
        out.close();