繁体   English   中英

如何在Thread中运行Web服务代码?

[英]how can i run Webservice code in Thread?

我想通过此代码从服务器获取一些数据:

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;
    }
}

但是应用程序中存在一些延迟和暂停,因此我想在线程中运行此代码,但是当我尝试执行此代码时,出现了一些错误,例如我无法返回结果或...

看看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); } } ... } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM