如何在自己的线程执行Web请求? [英] How to execute web request in its own thread?

查看:137
本文介绍了如何在自己的线程执行Web请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建Android应用程序有根据服务器响应在后台执行网络请求,然后处理接收到的数据和修改用户界面。

I am creating an android application which has to execute web requests in the background and then handle the received data and modify the user interface according to the server response.

在后台张贴请求和处理数据的目标是避免用户界面的冻结。目前,然而,我注意到用户界面冻结,所以我不知道逻辑工作,因为它应该。

The goal of posting requests and handling data in the background is to avoid the freezing of user interface. Currently however I notice that the user interface is freezing so I am not sure the logic is working as it is supposed to.

下面是code这是应该张贴请求,并在自己的线程处理响应,然后将数据传递到GUI中的一部分:

Here is the part of code which is supposed to post requests and handle responses in its own thread and then pass the data to GUI:

public class ServerConnection {

Queue<String> requests;

...

DefaultHttpClient httpClient;
HttpHost targetHost;

Handler handler;

ServerResponseHandler responseHandler;
Activity activity;

public ServerConnection(Activity activity){
    this.activity = activity;
    this.responseHandler = (ServerResponseHandler) activity;
    httpClient = new DefaultHttpClient();
    targetHost = new HttpHost(TARGET_DOMAIN, 80, "http");
    requests = new LinkedList<String>();
}



private Runnable requestSender = new Runnable(){

    @Override
    public void run() {
        if(!requests.isEmpty()){
            String requestString = requests.remove();
            HttpGet httpGet = new HttpGet(requestString);
            httpGet.addHeader("Accept", "text/xml");
            String encodingString = "testuser:testpass";
            String sEncodedString = Base64Coder.encodeString(encodingString);

            try{

                String sContent = fetchURL(requestString, sEncodedString);

                XMLParser xmlParser = new XMLParser();

                List <Product> products = xmlParser.getProducts(sContent);

                responseHandler.onProductsResponse(products);
            }
            catch(Exception ex){
                Log.e(TAG, ex.getMessage());
            }
        }
    }
};

public void sendRequest(String requestString){
    requests.add(requestString);
    handler = new Handler();
    handler.post(requestSender);
}

该方法sendRequest将(),是从实现ServerResponseHandler的主要活动调用。我想请求在自己的线程,并通过调用执行

The method sendRequest() is called from the main activity which implements ServerResponseHandler. I guess the request is executed in its own thread and by calling

responseHandler.onProductsResponse(产品);

responseHandler.onProductsResponse(products);

产品(从网上数据)列表传递给主要活动。总之,由于业绩不佳我会AP preciate如果有人可以纠正上述逻辑的任何可能的问题,或提出任何其他(更好)的选项。

the list of products (data from the web) is passed to main activity. Anyway due to poor performance I would appreciate if anyone could correct any possible issue in the logic above or suggest any other (better) option.

推荐答案

我建议你看一看的的AsyncTask类(可由于Android 1.5)。

I'd suggest you take a look at ASyncTask class (available since Android 1.5).

它简化了创建一个后台线程与同步GUI线程一旦完成的过程。

It simplifies the process of creating a background Thread that synchronizes with the GUI thread once it's complete.

您应该能够实现你使用code东西列表尝试一下这个

You should be able to achieve what you're trying using code something list this

private class DownloadFilesTask extends AsyncTask<String, List<Product>, Integer> {
     protected List<Products> doInBackground(String... requestStrings) {
        int count = requestStrings.length;
        int results = 0;
        for (int i = 0; i < count; i++) {
          String requestString = requestStrings[i];
          HttpGet httpGet = new HttpGet(requestString);
          httpGet.addHeader("Accept", "text/xml");
          String encodingString = "testuser:testpass";
          String sEncodedString = Base64Coder.encodeString(encodingString);
          try{
            String sContent = fetchURL(requestString, sEncodedString);
            XMLParser xmlParser = new XMLParser();
            List <Product> products = xmlParser.getProducts(sContent);
            results++;
            publishProgress(products);
          }
          catch(Exception ex){
            Log.e(TAG, ex.getMessage());
          }
        }
        return results;
     }

     protected void onProgressUpdate(Integer... progress) {
         // TODO You are on the GUI thread, and the first element in 
         // the progress parameter contains the last progress
         // published from doInBackground, so update your GUI
     }

     protected void onPostExecute(int result) {
       // Processing is complete, result contains the number of 
       // results you processed
     }
 }

和调用执行

new DownloadFilesTask().execute(url1, url2, url3);

这篇关于如何在自己的线程执行Web请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆