我们的想法是创建一个Android应用程序,它可以与现有服务器一起发送XML消息并获取XML响应。
以下是代码:
try {
URL url1 = null;
url1 = new URL("http://mysite.com/");
URLConnection urlc1 = url1.openConnection();
HttpURLConnection con1 = (HttpURLConnection) urlc1;
con1.setRequestMethod("POST");
con1.setUseCaches(false);
con1.setDoOutput(true);
con1.setDoInput(true);
con1.setRequestProperty("accept-charset", "UTF-8");
con1.setRequestProperty("content-type", "application/x-www-form-urlencoded");
XmlSerializer ser1 = Xml.newSerializer();
StringWriter writer = new StringWriter();
ser1.setOutput(writer);
ser1.startDocument("UTF-8", true);
ser1.startTag("", "request");
ser1.attribute("", "query", "open_session");
ser1.startTag("", "");
ser1.attribute("", "client", "name");
ser1.attribute("", "version", "1.0");
ser1.endTag("", "");
ser1.endTag("", "request");
ser1.endDocument();
String query = writer.toString();
con1.connect();
OutputStreamWriter out1 = new OutputStreamWriter(con1.getOutputStream());
out1.write(query);
out1.flush();
String result1 = null;
BufferedReader br1 = new BufferedReader(new InputStreamReader(con1.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br1.readLine()) != null){
sb.append(line);
}
br1.close();
result1 = sb.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
程序打开连接,创建登录请求XML,将其发送到服务器并获得XML答案。
但它无法正常工作。我得到的回应是:
<html><head><title>302 Found</title></head></body bg color="white"><center><h1>302 Found</h1></center><hr><center>nginx/1.0.0</center></body><html>
这不是服务器列出的错误。成功的答案应该是:
<result success="true">
<session-info time-out="number" id="number" start="number"/>
</result>
有趣的是,当我评论这部分代码时:
OutputStreamWriter out1 = new OutputStreamWriter(con1.getOutputStream());
out1.write(query);
out1.flush();
我得到了正确的XML错误答案:
<result success="false">
<error error-code="XML-01">
Wrong XML
</error>
</result>
你能帮帮我吗?
提前致谢。
答案 0 :(得分:0)
302 Found
是重定向消息,如果您使用HttpClient
,则可以在内部处理这些重定向。
查看https://stackoverflow.com/a/2560129/1321873,了解如何将XML发布到服务器。 (虽然他们发送的是SOAP XML,但发送普通XML的机制也是一样的 - 只需更改内容类型)