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

时间:2010-03-29 19:48:01

标签: php android json httpclient httpresponse

我目前正在尝试将一些来自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<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\"}

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

5 个答案:

答案 0 :(得分:11)

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

因此,使用:

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

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

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

答案 1 :(得分:4)

StringEntity s = new StringEntity(c.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
request.setEntity(s);

答案 2 :(得分: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) {
}

}

答案 3 :(得分:0)

更改

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

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

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

答案 4 :(得分:0)

尝试使用此代码完美运行

&#13;
&#13;
*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"
        }
    }
&#13;
&#13;
&#13;

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

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

    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

    }
}