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






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值