23

我目前正在尝试将一些数据从 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 - Forbidden 响应。

我尝试稍微更改 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\"}

谁能告诉我哪里出错了,或者是否有更好的方法来实现我想要做的事情?希望以上内容有意义!

4

5 回答 5

11

经过大量阅读和搜索后,我发现了问题所在,我相信在服务器上启用了 magic_quotes_gpc。

因此,使用:

json_decode(stripslashes($_POST['vehicle']));

在我上面的示例中,删除了斜杠并允许正确解码 JSON。

仍然不确定为什么发送 StringEntity 会导致 403 错误?

于 2010-03-29T22:38:31.473 回答
4
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
request.setEntity(s);
于 2010-12-09T02:23:22.507 回答
1

试试这个对我有用的代码

public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);

String json=obj.toString();

try {

    HttpPost httppost = new HttpPost(result.toString());
    httppost.setHeader("Content-type", "application/json");

    StringEntity se = new StringEntity(obj.toString()); 
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost.setEntity(se); 

    HttpResponse response = httpclient.execute(httppost);
    String temp = EntityUtils.toString(response.getEntity());
    Log.i("tag", temp);


} catch (ClientProtocolException e) {

} catch (IOException e) {
}

}

于 2012-02-22T06:35:58.890 回答
0

改变

(String url = "http://www.server.com/MainPage.php";)

(String url = "http://www.server.com/MainPage.php?";)

当您尝试将参数发送到 php 脚本时,末尾的问号是必要的。

于 2010-12-05T01:41:51.647 回答
0

试试这段代码,它工作得很好

*For HttpClient class* download jar file "httpclient-4.3.6.jar" and put in libs folder then
Compile:   dependencies {compile files('libs/httpclient-4.3.6.jar')}

repositories {
        maven {
            url "https://jitpack.io"
        }
    }

然后调用 HttpClient 类这个 AsyncTask 像这样:

私有类 YourTask 扩展 AsyncTask { private String error_msg = "服务器错误!";

    private JSONObject response;



    @Override
    protected Boolean doInBackground(String... params) {
        try {
            JSONObject mJsonObject = new JSONObject();
            mJsonObject.put("user_id", "user name");
            mJsonObject.put("password", "123456");
            String URL=" Your Link"

            //Log.e("Send Obj:", mJsonObject.toString());

            response = HttpClient.SendHttpPost(URL, mJsonObject);
            boolean status = response != null && response.getInt("is_error") == 0; // response

            return status;
        } catch (JSONException | NullPointerException e) {
            e.printStackTrace();
            mDialog.dismiss();
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean status) {
       // your code

    }
}
于 2016-11-04T09:28:55.740 回答