我最近开始做 Android 编程。我遇到了一个问题。目前我已经构建了一个名为“sendData”的 XML 字符串请求。此 sendData 需要发送到服务器以验证用户帐户是否有效。
目前,当我尝试发送请求时,我与服务器联系,但我收到默认的一般响应错误,这让我相信 XML 没有被正确发送。
public void postData(String sendData) {
// Create a new HttpClient and Post Header
System.out.println("SENDDATA" + sendData);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www......");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(0);
nameValuePairs.add(new BasicNameValuePair(sendData, sendData));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
inputStreamToString(response.getEntity().getContent());
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
}
catch (IOException e)
{
// TODO Auto-generated catch block
}
}
上面是我用来发送数据的代码。我相信问题可能发生在“尝试”部分。我在这个论坛上搜索过类似的问题,但找不到我要找的答案。
我们将不胜感激。
谢谢,
编辑:
在日志猫中。当我打印字符串时,它看起来像这样。
07-19 15:35:36.642: INFO/System.out(2204): <Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="1.0" xsi:noNamespaceSchemaLocation="http://www.example.com">
07-19 15:35:36.642: INFO/System.out(2204): <Identification>
07-19 15:35:36.642: INFO/System.out(2204): <UserID>username@example.com</UserID>
07-19 15:35:36.642: INFO/System.out(2204): <Password>password</Password>
07-19 15:35:36.642: INFO/System.out(2204): </Identification>
07-19 15:35:36.642: INFO/System.out(2204): <Service>
07-19 15:35:36.652: INFO/System.out(2204): <ServiceName>AccountVerify</ServiceName>
07-19 15:35:36.652: INFO/System.out(2204): <ServiceDetail/>
07-19 15:35:36.652: INFO/System.out(2204): </Service>
07-19 15:35:36.652: INFO/System.out(2204):
每个元素在 LogCat 中都有自己的行。这可能是问题所在吗?
最佳答案
我已经找到答案了。问题是进一步查看后,实际请求中没有发送任何信息。解决方案是删除数组并通过设置新实体来替换它。更改/工作代码如下:
try {
StringEntity se = new StringEntity(sendData);
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println("Message Sent!");
inputStreamToString(response.getEntity().getContent());
}
关于java - Android,通过 HTTP 将 XML 字符串发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6747627/