Android HttpUrlConnection 设置 POST 方法



我需要HttpUrlConnection才能使用 POST 方法,但它玩得不好。

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

在调试器中:

  • 在第一行,我按预期看到connection = null
  • 第二行我可以按预期看到connection.method = "GET"
  • 进一步,我看到connection.method = "GET"这是意料之外

如何让 HttpUrlConnection 使用 POST

溶液

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

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

解决方案

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

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

试试看:

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

附言我没有将硬编码字符串移动到常量以更好地理解。

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
}

}

相关内容

最新更新