在Android中为POST请求发送XML

时间:2011-01-05 13:28:28

标签: android xml http post http-post

在我的代码中,我让用户填写表单,然后将该表单保存在SD卡的XML文件中。

现在我需要将关于XML文件的信息作为POSTdata发送到服务器。

我该怎么做。

我已经在互联网上搜索并找到了一些示例代码,但我不知道如何添加SD卡上的XML文件。

public void sendtoRoutemobiel() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://mysite/");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //<-- need to replace this with
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));            //<-- the data on the XML-file 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));         //<-- (I think)

        HttpResponse response;
        response = httpclient.execute(httppost);
        String temp1 = EntityUtils.toString(response.getEntity());
        Log.d("Gabug", "Response: " + temp1);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:2)

您的实体必须是XML,而不是用于标题的值对:

 request.setEntity(new StringEntity(postData));

这是我的一个片段:

public static String getStringContent(String uri, String postData, 
        HashMap<String, String> headers) throws Exception {

        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost();
        request.setURI(new URI(uri));
        request.setEntity(new StringEntity(postData)); // HERE !!!!!! _______
        for(Entry<String, String> s : headers.entrySet())
        {
            request.setHeader(s.getKey(), s.getValue());
        }
        HttpResponse response = client.execute(request);
        // .. rest
 }