android okhttp 下载图片
时间: 2023-09-11 19:03:41 浏览: 110
Android使用okHttp(get方式)下载图片
在Android中使用OkHttp库下载图片需要创建一个OkHttp的工具类和一个实现回调接口的主Activity。首先,在工具类中创建一个静态的OkHttpClient对象,并通过该对象发送请求并获取响应体。然后,将响应体转化为流,再将流转化为Bitmap对象。接下来,在主Activity中设置ImageView的初始图片,然后执行AsyncTask来下载图片。在AsyncTask的doInBackground方法中使用工具类获取图片的Bitmap对象,并将其返回。最后,在AsyncTask的onPostExecute方法中通过回调接口将Bitmap对象设置给ImageView。
以下是一个示例代码:
工具类OkHttpDownload.java:
```java
public class OkHttpDownload {
private static OkHttpClient okHttpClient;
public static Bitmap getImageBitmap(String urlPath) {
Bitmap bitmap = null;
okHttpClient = new OkHttpClient();
URL url = null;
try {
url = new URL(urlPath);
//获取请求对象
Request request = new Request.Builder().url(url).build();
//获取响应体
ResponseBody responseBody = okHttpClient.newCall(request).execute().body();<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [安卓第七天---okhttp的简单使用及异步任务(Asynctask)下载图片](https://blog.csdn.net/Autumn_leavess/article/details/84145839)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文