首页 > 解决方案 > 将 JSON 数据从 Android 发送到 PHP 脚本

问题描述

我正在使用此代码发送带有 JSON 对象的数据,但我的代码说我发送 null 'jsonResponse is always null'。我看不出我的问题出在哪里,我不确定这行代码 String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());EntityUtils 类在 android 中是否已弃用。

public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {

    String url = "http://192.168.52.170/socketIO/examples/chat/public/";

    @Override
    protected JSONObject doInBackground(JSONObject... data) {
        JSONObject json = data[0];
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

        JSONObject jsonResponse = null;
        HttpPost post = new HttpPost(url);
        try {
            StringEntity se = new StringEntity("json="+json.toString());
            post.addHeader("content-type", "application/json");
            post.setEntity(se);

            HttpResponse response;
            response = client.execute(post);
            String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

            jsonResponse = new JSONObject(resFromServer);
            Log.i("Response from server", jsonResponse.getString("msg"));
        } catch (Exception e) { e.printStackTrace();}

        return jsonResponse;
    }

}

标签: androidjsonhttp-post

解决方案


推荐阅读