Android HttpUrlConnection设置POST方法

时间:2016-02-08 19:23:09

标签: android http-post httpurlconnection

我需要HttpUrlConnection才能使用 POST 方法,但它的播放效果不佳。

connection = (HttpURLConnection) link.openConnection();
connection.setRequestMethod("POST");
...

在调试器中:

  • 在第一行,我按预期connection = null看到了
  • 第二行我可以按预期看到connection.method = "GET"
  • 我还看到了connection.method = "GET"这不是预期的

如何让HttpUrlConnection使用 POST

解决方案

如果您在" HTTPS"上打开HttpUrlconnection协议,连接永久覆盖与" GET"。

的连接

Via" HTTP"连接将允许" POST"手动设置的方法。

3 个答案:

答案 0 :(得分:1)

试一试:

public static String executePostHttpRequest(final String path, Map<String, String> params) throws ClientProtocolException, IOException {
    String result = null;
    HttpURLConnection urlConnection = null;
    try {
        String postData = getQuery(params);
        byte[] postDataBytes = postData.getBytes("UTF-8");

        URL url = new URL(path);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(30000);
        urlConnection.setReadTimeout(30000);
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        urlConnection.setRequestProperty("charset", "UTF-8");
        urlConnection.setRequestProperty("Content-Length", Integer.toString(postDataBytes.length));

        OutputStream out = urlConnection.getOutputStream();
        out.write(postDataBytes);
        out.close();
        result = readStream(urlConnection.getInputStream());
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return result;
}

其中:

private static String getQuery(Map<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder(); 
    boolean haveData = params != null && params.size() > 0;
    if (haveData) {
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()){
            String value = entry.getValue();
            if (value != null) {
                if (first) {
                     first = false;
                } else {
                     result.append("&");
                }
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(value, "UTF-8"));
            }
        }
    }
    return result.toString();
}

P.S。我没有将硬编码的字符串移动到常量以便更好地理解。

答案 1 :(得分:1)

解决方案

如果您在“HTTPS”协议上打开HttpUrlconnection,则连接将永久覆盖与“GET”的连接。

通过“HTTP”,如果手动设置,连接将允许“POST”方法。

答案 2 :(得分:0)

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

}