在android中执行从服务器获取

在android中执行从服务器获取

本文介绍了在android中执行从服务器获取/发布JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



发布:

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

获取:

  HttpGet httpGet = new HttpGet(MYDOMAIN); 
HttpResponse响应= httpClient.execute(httpGet);


解决方案

HTTP请求必须异步完成。
首先确保您的AndroidManifest.xml中有INTERNET权限

然后为Request创建一个类,以便重用它$ p

$

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


Callback.JSONCallback回调;
字符串网址;
字符串类型;

public请求(String类型,String url,Callback.JSONCallback回调){
this.callback = callback;
extension = url;
this.type = type;
}

//做什么Async,在这种情况下是POST / GET $ b $保护字符串doInBackground(List< NameValuePair> ... pairs){

HttpClient httpClient = new DefaultHttpClient();

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

尝试{
//添加您的数据
httpPost.setEntity(new UrlEncodedFormEntity(pairs [0],UTF-8));

//执行HTTP发布请求
HttpResponse响应= httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity());

返回结果;

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

字符串结果= EntityUtils.toString(response.getEntity());

返回结果;

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

return;



//在AsyncTask
保护void onPostExecute(String feed){
JSONObject JSON = null;
尝试{
JSON = new JSONObject(feed);
} catch(JSONException e){
e.printStackTrace();
}
callback.call(JSON);
}

}

然后创建一个名为callback的类并创建一个接口,如下所示:

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

}

然后使用POST或GET。服务器应该返回JSON,然后你可以按照你的意愿解析它。

  List< NameValuePair> nameValuePairList = new ArrayList< NameValuePair>(2); 
//不是manditory,可以用于象token这样的东西。
nameValuePairList.add(new BasicNameValuePair(ID,VALUE));
new请求(POST,URL,new Callback.JSONCallback(){
@Override
public void call(JSONObject JSON){
try {
//在这里解析JSON

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

列表< NameValuePair> nameValuePairList = new ArrayList< NameValuePair>(2);
//不是manditory,可以用于象token这样的东西。
nameValuePairList.add(new BasicNameValuePair(ID,VALUE));
new请求(GET,URL,new Callback.JSONCallback(){
@Override
public void call(JSONObject JSON){
try {
//在这里解析JSON

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


What is the most efficient method to get a JSON response when using http get/post. Obviously they must be done asynchronously.

Note: I already have internet permissions enabled in the manifest file.

Posting:

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

Getting:

HttpGet httpGet = new HttpGet("MYDOMAIN");
HttpResponse response = httpClient.execute(httpGet);
解决方案

HTTP Requests have to be done Asynchronously.First make sure you have INTERNET Permission in your AndroidManifest.xml

Then make a class for Request so you can reuse it

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

}

Then make a class called callback and make an interface like so:

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

}

Then either use POST or GET. Server should return JSON and then you can parse it as you wish

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

这篇关于在android中执行从服务器获取/发布JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:48