使用okhttp将接收到的数据显示到textView上
时间: 2023-02-16 16:29:25 浏览: 87
下面是一个示例代码,可以使用 OkHttp 将接收到的数据显示到 TextView 上:
```
OkHttpClient client = new OkHttpClient();
String url = "http://www.example.com";
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
final String responseData = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(responseData);
}
});
}
});
```
在上面的代码中,我们首先创建了一个 OkHttpClient 对象,然后使用该对象发送一个 HTTP 请求,最后在 onResponse() 方法中将响应数据显示到 TextView 上。
注意:上面的代码需要在Android的主线程中执行,所以使用runOnUiThread() 方法将更新 TextView 的操作放到主线程中执行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)