首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在线程中运行Webservice代码?

如何在线程中运行Webservice代码?
EN

Stack Overflow用户
提问于 2015-06-21 04:30:29
回答 1查看 34关注 0票数 0

我想用下面的代码从服务器获取一些数据:

代码语言:javascript
运行
复制
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;
    }
}

但是在应用程序中有一些延迟和暂停,所以我想在线程中运行这段代码,但当我试图这样做时,我得到了一些错误,例如我无法返回结果或...

EN

回答 1

Stack Overflow用户

发布于 2015-06-21 04:33:27

看一看AsyncTask

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

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

公共类HttpExampleActivity扩展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) ();} //当用户点击按钮时,调用。//在尝试获取URL之前,请确保存在网络连接。public void URL (视图视图){ //从UI的文本字段获取myClickHandler。getSystemService(Context.CONNECTIVITY_SERVICE);stringUrl = urlText.getText().toString();ConnectivityManager connMgr = (ConnectivityManager) String NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isConnected()) { new DownloadWebpageTask().execute(stringUrl);} else {textView.setText(“没有可用的网络连接。”);} //使用AsyncTask在主UI线程之外创建任务。此任务接受// URL字符串并使用它创建一个HttpUrlConnection。一旦建立了连接,AsyncTask就以InputStream的形式下载网页的内容。最后,通过异步任务的onPostExecute方法将InputStream转换为//显示在UI中的字符串。私有类DownloadWebpageTask扩展了AsyncTask,String>{ @Override protected String doInBackground(String...urls) { // params来自execute()调用: params是url。try { return downloadUrl (IOException );} catch ( URL e) { return“无法检索网页。URL可能无效。”;} // onPostExecute显示AsyncTask的结果。@Override protected void result(String OnPostExecute){ textView.setText( result);}} ... }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30958578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档