在Android中,如何使用URL编码的表单数据进行POST请求而不使用UrlEncodedFormEntity?

14
我有一个已经以正确的URLEncoded Form格式编码的字符串,并希望通过Android的POST请求发送到PHP服务器。我知道在Android上发送URL编码表单的方法使用UrlEncodedFormEntity,并且我知道如何使用它。但问题是数据已经被URL编码和连接起来,因此使用UrlEncodedFormEntity需要额外的工作将其转换为ListNameValuePairs,我不想这样做。
那么,我该如何将这个字符串作为内容体发送到服务器,以进行正确的POST请求呢?
我已经尝试过使用StringEntity,但PHP服务器没有收到任何数据(空的$_POST对象)。
我正在对http://test.lifewanted.com/echo.json.php进行测试,该网站只是一个回显接口。
<?php echo json_encode( $_REQUEST );

这是一个已经进行过编码的数据示例:

partnerUserID=email%40example.com&partnerUserSecret=mypassword&command=Authenticate

1个回答

15

如果您不介意使用HttpURLConnection而不是(推荐的)HttpClient,则可以按照以下方式执行:

public void performPost(String encodedData) {
    HttpURLConnection urlc = null;
    OutputStreamWriter out = null;
    DataOutputStream dataout = null;
    BufferedReader in = null;
    try {
        URL url = new URL(URL_LOGIN_SUBMIT);
        urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestMethod("POST");
        urlc.setDoOutput(true);
        urlc.setDoInput(true);
        urlc.setUseCaches(false);
        urlc.setAllowUserInteraction(false);
        urlc.setRequestProperty(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
        urlc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        dataout = new DataOutputStream(urlc.getOutputStream());
        // perform POST operation
        dataout.writeBytes(encodedData);
        int responseCode = urlc.getResponseCode();
        in = new BufferedReader(new InputStreamReader(urlc.getInputStream()),8096);
        String response;
        // write html to System.out for debug
        while ((response = in.readLine()) != null) {
            System.out.println(response);
        }
        in.close();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5
在Gingerbread(Android 2.3)及更高版本中,HttpURLConnection是最佳选择。考虑到Apache HttpClient已被弃用。 - Elliott Hughes
1
我刚意识到我从未接受这个答案。这对我非常有效。谢谢! - Oz.
2
两件事情:InputStreamReader 根据 Android 的文档(http://developer.android.com/reference/java/io/InputStreamReader.html)已经被缓冲,所以不需要使用 BufferedReader。而且,根据 Android 的文档,在使用完毕后,必须调用 HttpURLConnection 的 disconnect() 方法来释放资源。 - Gonan

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