将JSON数据从Android发送到PHP脚本

时间:2019-06-11 06:24:26

标签: android json http-post

我正在使用此代码通过JSON对象发送数据,但是我的代码显示我发送了空'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;
    }

}

0 个答案:

没有答案