2011-02-16 121 views
8

有一个相关的问题,但我无法清楚地得到答案。Android,通过HTTP POST方法发送和接收XML

我想发布一个简短的XML代码

<aaaLogin inName="admin" inPassword="admin123"/> 

通过HTTP特定的URL地址。 Web服务会将我发回的XML代码。重要的部分是我将解析接收到的XML,并且我想将它作为一个文件存储。

// Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://192.168.192.131/"); //URL address 

    StringEntity se = new StringEntity("<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>",HTTP.UTF_8); //XML as a string 
    se.setContentType("text/xml"); //declare it as XML 
    httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8"); 
    httppost.setEntity(se); 

    BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient .execute(httppost); 
    tvData.setText(httpResponse.getStatusLine().toString()); //text view is expected to print the response 

接收响应有问题。此外,我没有写任何东西来将接收到的XML保存为文件。有人可以编写代码片段吗?

回答

3

可以使用得到响应的内容:

String responseXml = EntityUtils.toString(httpResponse.getEntity()); 

然后你可以使用的东西like this写一个文件。

有什么毛病接收既然你没有带说什么是错误的接收是有些困难来帮助你这一点上,响应响应

13

好的,我发布了这个问题后不久就想通了。 这里此代码工作正常:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://192.168.192.131/"); 

try { 
    StringEntity se = new StringEntity("<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8); 
    se.setContentType("text/xml"); 
    httppost.setEntity(se); 

    HttpResponse httpresponse = httpclient.execute(httppost); 
    HttpEntity resEntity = httpresponse.getEntity(); 
    tvData.setText(EntityUtils.toString(resEntity));   
} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
}