在 android 中从服务器执行 get/post 以获得 JSON 响应

Performing get/post from server for JSON response in android

使用 http get/post 时获得 JSON 响应的最有效方法是什么。显然它们必须异步完成。

注意:我已经在清单文件中启用了互联网权限。

发帖:

HttpPost httpPost = new HttpPost("MYDOMAIN");
HttpResponse response = httpClient.execute(httpPost);

获得:

HttpGet httpGet = new HttpGet("MYDOMAIN");
HttpResponse response = httpClient.execute(httpGet);

HTTP 请求必须异步完成。 首先确保您在 AndroidManifest.xml

中具有 INTERNET 权限

然后为 Request 创建一个 class 以便您可以重复使用它

public class Request extends AsyncTask<List<NameValuePair>, Void, String> {


    Callback.JSONCallback callback;
    String url;
    String type;

    public Request(String type, String url, Callback.JSONCallback callback) {
        this.callback = callback;
        extension = url;
        this.type = type;
    }

    // What to do Async, in this case its POST/GET
    protected String doInBackground(List<NameValuePair>... pairs) {

        HttpClient httpClient = new DefaultHttpClient();

        if (type.equals("POST")) {
            HttpPost httpPost = new HttpPost(url);

            try {
                // Add your data
                httpPost.setEntity(new UrlEncodedFormEntity(pairs[0], "UTF-8"));

                // Execute HTTP Post Request
                HttpResponse response = httpClient.execute(httpPost);
                String result = EntityUtils.toString(response.getEntity());

                return result;

            } catch (Exception e) {
                Log.v("error", e.toString());
            }
        } else if (type.equals("GET")) {
            try {
                HttpGet httpGet = new HttpGet(url);
                HttpResponse response = httpClient.execute(httpGet);
                response.getStatusLine().getStatusCode();

                String result = EntityUtils.toString(response.getEntity());

                return result;

            } catch (Exception e) {
                Log.v("error", e.toString());
            }
        }

        return "";

    }

    // What to do after AsyncTask
    protected void onPostExecute(String feed) {
        JSONObject JSON = null;
        try {
            JSON = new JSONObject(feed);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        callback.call(JSON);
    }

}

然后创建一个 class 调用回调并创建一个如下所示的接口:

public class Callback {
    public interface JSONCallback {
        void call(JSONObject JSON);
    }

}

然后使用 POST 或 GET。服务器应该 return JSON 然后你可以随意解析它

List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(2);
// Not manditory, can be used for things like token, etc.
nameValuePairList.add(new BasicNameValuePair("ID", "VALUE"));
new Request("POST", "URL", new Callback.JSONCallback() {
    @Override
    public void call(JSONObject JSON) {
        try {
            // Parse JSON here

        } catch (JSONException e) {
            Log.v("error", e.toString());
        }
    }
}).execute(nameValuePairList);

List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(2);
// Not manditory, can be used for things like token, etc.
nameValuePairList.add(new BasicNameValuePair("ID", "VALUE"));
new Request("GET", "URL", new Callback.JSONCallback() {
    @Override
    public void call(JSONObject JSON) {
        try {
            // Parse JSON here

        } catch (JSONException e) {
            Log.v("error", e.toString());
        }
    }
}).execute(nameValuePairList);