实现android异步调用WEB API的方法

在一般应用中我们很多时候都会遇到利用网络请求实现和客户交互的操作,由于网络的请求需要或长或短的时间等待,所以我们一般会把显示界面和网络请求取得数据的操作放在不同的线程上操作,把界面的操作放在主线程,而从网络取得数据的操作就放在另外一个子线程中操作,网上说明这个实现方法的资料过于贫乏,所以我把实验代码贴出来

下面的类使用一个单独的线程从主界面线程的HTTP调用Android的AsyncTask。事实上,在较新版本的Android上你是无法在主线程上调用的,你会得到一个异常 android.os.networkonmainthreadexception

public class ApiCall extends AsyncTask {
    private String result;
    protected Long doInBackground(URL... urls) {
int count = urls.length;
    long totalSize = 0;
    StringBuilder resultBuilder = new StringBuilder();
        for (int i = 0; i < count; i++) {
        try {
            // Read all the text returned by the server
                InputStreamReader reader = new InputStreamReader(urls

[i].openStream());
                BufferedReader in = new BufferedReader(reader);
                String resultPiece;
                while ((resultPiece = in.readLine()) != null) {
                resultBuilder.append(resultPiece);
                }
                in.close();
             } catch (MalformedURLException e) {
             e.printStackTrace();
             } catch (IOException e) {
             e.printStackTrace();
             }
             // if cancel() is called, leave the loop early
             if (isCancelled()) {
             break;
             }
         }
         // save the result
         this.result = resultBuilder.toString();
         return totalSize;
     }
    protected void onProgressUpdate(Integer... progress) {
        // update progress here
    }
// called after doInBackground finishes
    protected void onPostExecute(Long result) { 
    Log.v("result, yay!", this.result);
    }
}
调用方法很简单,如下:

URL url = null;
try {
    url = new URL("http://search.twitter.com/search.json?q=@justinjmcc");
} catch (MalformedURLException e) {
    e.printStackTrace();
}
new ApiCall().execute(url);







发布了40 篇原创文章 · 获赞 6 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章