0

我注意到,与与同一服务器通信的应用程序相比,我的 http 请求往往花费大量时间。这让我的应用程序感觉迟缓,我想知道是否有更好的方法来发出这些请求和更新 UI。

目前我使用这种方法发出帖子请求

public String postRequest(List<NameValuePair> nameValuePairs, String method_name) {

    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.mysite.com/api/"+method_name);
    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Authorization", "Basic somestuff");

    try {
        // Add your data           
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        result = rd.readLine();

        return result;
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
    return null;
}

在我的 UI 线程(即我的 Fragment 类)中,我在这样的异步任务中使用它

class MakeRequest extends AsyncTask<Integer, Integer, String> {

    protected String doInBackground(Integer... counter) {           
        String result = "";
        String method_name = "";

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", value));
            nameValuePairs.add(new BasicNameValuePair("name", name));
            method_name = "petition/setPetition";

            result = fixr.postRequest(nameValuePairs, method_name);

            JSONObject jsonFile = new JSONObject(result);
            if(!jsonFile.has("error")){ 

                //Parse JSON using GSON

                return "success";
            }else{
                return jsonFile.getString("error");
            }
        } catch (Exception e) {
            e.printStackTrace();                
        }

        return null;
    }

    protected void onPostExecute(String jsonResult) {

        try {   

            if(jsonResult != null){                 
                //update UI
            }else{
                //Error message
            }               
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我想对此进行优化,以便用户可以在我的应用程序上获得非常流畅的体验。我对使用第三方 http 库持开放态度,或者是否还有反对使用 AysncTasks 的论点,也许是runOnUiThread()相反。

4

2 回答 2

0

试试排球队友!我从 AsyncTasks 更改为 Volley 库,我对整体体验感到非常满意!

排球库

于 2013-08-14T08:30:44.740 回答
0

Volley 库更好,http、https 等
https://developers.google.com/live/shows/474338138
非常迷你的示例:https ://github.com/ogrebgr/android_volley_examples/blob/master/src/com/ github/volley_examples/Act_SimpleRequest.java

于 2013-08-14T08:38:56.837 回答