我试图通过使用Android设备将一些数据发送到使用Apache/MySQL配置的网页。下面是一个代码片段我使用(IP地址为fictionnal):Android中的HttpPost部分工作
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("http://10.1.1.2/test.php");
new Thread(new Runnable() {
public void run() {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("submitted", "1"));
nameValuePairs.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
nameValuePairs.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
nameValuePairs.add(new BasicNameValuePair("country", country));
nameValuePairs.add(new BasicNameValuePair("adminArea", admin));
nameValuePairs.add(new BasicNameValuePair("subAdminArea", subAdmin));
nameValuePairs.add(new BasicNameValuePair("city", city));
nameValuePairs.add(new BasicNameValuePair("zip", zip));
nameValuePairs.add(new BasicNameValuePair("address", adrs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = null;
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}).start();
这段代码被执行一次我按下“提交”按钮,插入服务器端的数据库。我遇到的问题是,我只收到部分发送的数据,并且必须多次按下“提交”按钮以确保所有数据都已插入。举个例子,我第一次点击按钮时,只插入了国家。然后adminArea,那么“subAdminArea”,等等
难道是上面所示的代码有问题或可能是在服务器端有问题?
如果你有机会到服务器,为什么不签什么是通过查看服务器日志或使用Wireshark的在服务器到达?通过这种方式,您可以确认服务器正在接收的内容,这可以帮助您更好地了解问题发生的位置。 – 2012-01-31 15:35:07
同意,看不出你的代码有什么问题 - 虽然我建议使用AsyncTask而不是线程 - 并且认为你需要检查服务器端的东西。 – 2012-01-31 16:51:25
我发现了这个问题。对数据库进行的一些查询返回了导致一些错误的空结果。由于我没有接口来查看服务器的响应,所以我没有看到这些错误。通过查看日志有助于发现问题。谢谢您的帮助。 – SimCity 2012-01-31 17:10:51