2015-06-20 17 views
0

我想用这个代码从服务器获取一些数据:我如何在线程中运行Webservice代码?

public class Webservice { 

    public static String readUrl(String url, ArrayList<NameValuePair> params) { 
     try { 
      HttpClient client = new DefaultHttpClient(); 
      HttpPost method = new HttpPost(url); 

      if (params != null) { 
       method.setEntity(new UrlEncodedFormEntity(params)); 
      } 

      HttpResponse response = client.execute(method); 

      InputStream inputStream = response.getEntity().getContent(); 
      String result = convertInputStreamToString(inputStream); 

      return result; 
     } 
     catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 


    private static String convertInputStreamToString(InputStream inputStream) { 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
      StringBuilder builder = new StringBuilder(); 

      String line = ""; 

      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
      } 

      return builder.toString(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 
} 

但有一些延迟,并在应用程序暂停,所以我想运行的线程的代码,但是当我试图做到这一点,我得到了一些错误,例如我不能返回的结果或...

回答

1

AsyncTask看看:

网络操作可能涉及不可预测的延迟。为了防止这种 导致糟糕的用户体验,请始终在与UI不同的线程上执行网络操作 。 AsyncTask类提供了从UI线程触发新任务的最简单方法之一。有关此主题的更多 讨论,请参阅博客文章多线程处理 性能。

在下面的代码片段中,myClickHandler()方法调用新的 DownloadWebpageTask()。execute(stringUrl)。 DownloadWebpageTask 类是AsyncTask的子类。

public class HttpExampleActivity extends Activity { 
private static final String DEBUG_TAG = "HttpExample"; 
private EditText urlText; 
private TextView textView; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    urlText = (EditText) findViewById(R.id.myUrl); 
    textView = (TextView) findViewById(R.id.myText); 
} 

// When user clicks button, calls AsyncTask. 
// Before attempting to fetch the URL, makes sure that there is a network connection. 
public void myClickHandler(View view) { 
    // Gets the URL from the UI's text field. 
    String stringUrl = urlText.getText().toString(); 
    ConnectivityManager connMgr = (ConnectivityManager) 
     getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     new DownloadWebpageTask().execute(stringUrl); 
    } else { 
     textView.setText("No network connection available."); 
    } 
} 

// Uses AsyncTask to create a task away from the main UI thread. This task takes a 
// URL string and uses it to create an HttpUrlConnection. Once the connection 
// has been established, the AsyncTask downloads the contents of the webpage as 
// an InputStream. Finally, the InputStream is converted into a string, which is 
// displayed in the UI by the AsyncTask's onPostExecute method. 
private class DownloadWebpageTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... urls) { 

     // params comes from the execute() call: params[0] is the url. 
     try { 
      return downloadUrl(urls[0]); 
     } catch (IOException e) { 
      return "Unable to retrieve web page. URL may be invalid."; 
     } 
    } 
    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(String result) { 
     textView.setText(result); 
    } 
} 
... } 
+0

谢谢你,但我该如何使用PARAMS –

+0

看一看这一http://stackoverflow.com/questions/7294533/passing-parameters-to-asynctask问题 –