Android,通过HTTP POST方法发送和接收XML

cev*_*rda 8 xml android http http-post

有一个相关的问题,但我无法清楚地得到答案.

我想POST一个简短的xml代码

<aaaLogin inName="admin" inPassword="admin123"/>
Run Code Online (Sandbox Code Playgroud)

通过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
Run Code Online (Sandbox Code Playgroud)

收到回复有问题.此外,我没有写任何东西来保存收到的XML作为文件.有人可以编写代码片段吗?

cev*_*rda 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();
}
Run Code Online (Sandbox Code Playgroud)


dav*_*e.c 3

您可以使用以下方式获取响应的内容:

String responseXml = EntityUtils.toString(httpResponse.getEntity());
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用类似以下内容将其写入文件。

接收响应时出现问题

由于您没有说明收到回复有什么问题,因此在这一点上很难帮助您。