有一个相关的问题,但我无法清楚地得到答案。
我想发布一个简短的 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 保存为文件。有人可以写一段代码吗?
最佳答案
好的,我发布这个问题后很快就想通了。 这段代码在这里工作正常:
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();
}
关于Android,通过 HTTP POST 方法发送和接收 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5013373/