如何知道何时收到服务器的响应?

时间:2014-05-15 18:10:24

标签: android multithreading android-webview

好的,我想要的是向我的服务器询问网址,并在WebView上加载该网址,但会出现问题:当您运行http请求时,您需要在单独的线程中执行此操作,并且需要在UI线程中运行loadUrl()。那么,我该如何做首先发出请求然后加载网址?

代码不在Activity中,因此我无法调用runOnUiThread(Runnable)

我该怎么做?

编辑:正如Alécio建议的那样,最好不要在自定义视图中包含太多代码,所以我想要做的是创建一个方法,允许我在应用程序收到服务器的响应时传递URL。我用于请求的代码是:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://requesturl.com");
try {
    HttpResponse response = client.execute(post);
    InputStream content = response.getEntity().getContent();
    String url = getStringFromInputStream(content);
    //web.loadUrl(url);     
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

那么,有可能知道何时收到回复?

1 个答案:

答案 0 :(得分:1)

WebView是一个UI组件,它必须位于Activity或Fragment的上下文中,因此UI线程中的loadUrl()是正常的。

如果要进行服务器调用,在UI上显示某些内容之前处理响应,则可以使用常规选项使用HttpURLConnection连接到服务器URL。请参阅以下示例代码:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
 readStream(in);
finally {
 urlConnection.disconnect();
}
}

在此示例中,您确实需要在后台线程中执行它。永远不要从UI线程。