Android, send and receive XML via HTTP POST method

感情迁移 提交于 2019-11-26 20:16:19

问题


There is a relevant question, but I could not get the answer clearly.

I would like to POST a short xml code

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

to a specific URL address over HTTP. The Web service will send me back a XML code. The important part is that I will parse the received XML, and I want to store that as a file.

    // 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

there is something wrong with receiving the response. Besides, I did not write anything to save the received XML as a file. Can someone write a code snippet?


回答1:


Ok, I have figured out soon after I posted this question. This code here works fine:

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



回答2:


You can get the content of the response using:

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

You can then write this to a file using something like this.

there is something wrong with receiving the response

Since you havn't said what is wrong with receiving the response it's somewhat difficult to help you with this point.




回答3:


Why not use Spring RestTemplate in Spring for Android?



来源:https://stackoverflow.com/questions/5013373/android-send-and-receive-xml-via-http-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!