我一直在努力将 JSON 对象从 android 上的应用程序发送到 php 文件(本地托管)。php 位与我的问题无关,因为wireshark 没有记录我的应用程序中的任何活动(eclipse/ADK 中的仿真),而且几乎可以肯定与我的发送方法有关:
try {
JSONObject json = new JSONObject();
json.put("id", "5");
json.put("time", "3:00");
json.put("date", "03.04.12");
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://localhost/datarecieve.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
我已经根据我找到的一个示例对其进行了修改,所以我确信我已经采用了一些非常好的代码并对其进行了修改。我了解多线程的要求,因此我的应用程序不会挂起和死机,但不确定它的实现。使用 Asynctask 会解决这个问题,还是我错过了其他重要的事情?
感谢您提供任何帮助。