我正在尝试从和android应用程序向php服务器发送一些数据(两者都由我控制)。
应用程序中的表单上收集了大量数据,这些数据将写入数据库。这都管用。
在我的主代码中,首先我创建了一个jsonobject(在本例中,我在这里对它进行了裁剪):
JSONObject j = new JSONObject();
j.put("engineer", "me");
j.put("date", "today");
j.put("fuel", "full");
j.put("car", "mine");
j.put("distance", "miles");
接下来,我将对象传递给发送,并接收响应:
String url = "http://www.server.com/thisfile.php";
HttpResponse re = HTTPPoster.doPost(url, j);
String temp = EntityUtils.toString(re.getEntity());
if (temp.compareTo("SUCCESS")==0)
{
Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();
}
HttpPoster类:
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
HttpResponse response;
response = httpclient.execute(request);
return response;
}
这将得到一个响应,但服务器将返回一个403禁止的响应。
我试着改变dopost函数一点(这实际上更好一点,正如我所说,我有很多要发送的,基本上是同一个表单的3个不同的数据-所以我创建了3个jsonobjects,每个表单条目一个-条目来自db,而不是我使用的静态示例)。
首先我把电话改了一下:
String url = "http://www.myserver.com/ServiceMatalan.php";
Map kvPairs = new HashMap();
kvPairs.put("vehicle", j.toString());
// Normally I would pass two more JSONObjects.....
HttpResponse re = HTTPPoster.doPost(url, kvPairs);
String temp = EntityUtils.toString(re.getEntity());
if (temp.compareTo("SUCCESS")==0)
{
Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();
}
好的,对dopost函数的更改:
public static HttpResponse doPost(String url, Map kvPairs) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if (kvPairs != null && kvPairs.isEmpty() == false)
{
List nameValuePairs = new ArrayList(kvPairs.size());
String k, v;
Iterator itKeys = kvPairs.keySet().iterator();
while (itKeys.hasNext())
{
k = itKeys.next();
v = kvPairs.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
HttpResponse response;
response = httpclient.execute(httppost);
return response;
}
好的,这返回一个响应200
int statusCode = re.getStatusLine().getStatusCode();
但是,服务器上接收到的数据无法解析为json字符串。我认为格式不好(这是我第一次使用json):
如果在php文件中,我在$_post['vehicle']上执行echo,会得到以下结果:
{\"date\":\"today\",\"engineer\":\"me\"}
有谁能告诉我哪里出错了,或者有没有更好的方法来实现我的目标?希望上面说的有道理!