Android JSON HttpClient 使用 HttpResponse 将数据发送到 PHP 服务器

发布于 2024-08-27 04:45:00 字数 3079 浏览 10 评论 0原文

我目前正在尝试从 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;
}

这会得到响应,但服务器正在返回a 403 - 禁止响应。

我尝试稍微更改一下 doPost 函数(这实际上好一点,正如我所说,我有很多要发送,基本上是 3 个具有不同数据的相同表单 - 所以我创建了 3 个 JSONObject,每个表单条目一个 - 条目来自数据库而不是我正在使用的静态示例)。

首先,我稍微改变了调用:

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\"}

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

I am currently trying to send some data from and Android application to a php server (both are controlled by me).

There is alot of data collected on a form in the app, this is written to the database. This all works.

In my main code, firstly I create a JSONObject (I have cut it down here for this example):

JSONObject j = new JSONObject();
j.put("engineer", "me");
j.put("date", "today");
j.put("fuel", "full");
j.put("car", "mine");
j.put("distance", "miles");

Next I pass the object over for sending, and receive the response:

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();
}

The HTTPPoster class:

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;
}

This gets a response, but the server is returning a 403 - Forbidden response.

I have tried changing the doPost function a little (this is actually a little better, as I said I have alot to send, basically 3 of the same form with different data - so I create 3 JSONObjects, one for each form entry - the entries come from the DB instead of the static example I am using).

Firstly I changed the call over a bit:

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();
}

Ok so the changes to the doPost function:

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;
}

Ok So this returns a response 200

int statusCode = re.getStatusLine().getStatusCode();

However the data received on the server cannot be parsed to a JSON string. It is badly formatted I think (this is the first time I have used JSON):

If in the php file I do an echo on $_POST['vehicle'] I get the following:

{\"date\":\"today\",\"engineer\":\"me\"}

Can anyone tell me where I am going wrong, or if there is a better way to achieve what I am trying to do? Hopefully the above makes sense!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

多情癖 2024-09-03 04:45:00

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

因此,使用:

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

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

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

After lots of reading and searching I have found the problem to be with, I beleive magic_quotes_gpc being enabled on the server.

Thus, using:

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

In my example above removes the slashes and allows the JSON to be decoded properly.

Still not sure why sending a StringEntity causes a 403 error?

终难愈 2024-09-03 04:45:00
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
request.setEntity(s);
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
request.setEntity(s);
橘和柠 2024-09-03 04:45:00

当您尝试将参数发送到 php 脚本时,需要更改

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

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

末尾的问号

Change

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

to

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

Question mark at the end is necessary when you're trying to send parameters to php script.

﹏半生如梦愿梦如真 2024-09-03 04:45:00

尝试一下这个代码,它工作得很好

*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:

private class YourTask extends 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

    }
}

Try this code it works perfectly

*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"
        }
    }

then call HttpClient class this AsyncTask Like this:

private class YourTask extends AsyncTask {
private String error_msg = "Server error!";

    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

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文