Android JSON HttpClient 使用 HttpResponse 将数据发送到 PHP 服务器
2022-08-30 18:35:49
我目前正在尝试将一些数据从和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,每个表单条目一个 - 条目来自数据库而不是我正在使用的静态示例)。
首先,我稍微改变了一下电话:
String url = "http://www.myserver.com/ServiceMatalan.php";
Map<String, String> kvPairs = new HashMap<String, String>();
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<String, String> kvPairs) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if (kvPairs != null && kvPairs.isEmpty() == false)
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
String k, v;
Iterator<String> 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']上做了一个回显,我得到以下结果:
{\"date\":\"today\",\"engineer\":\"me\"}
谁能告诉我哪里出了问题,或者是否有更好的方法来实现我想要做的事情?希望以上是有道理的!