使用OKHTTP,网上抓图
时间: 2024-12-01 08:11:30 浏览: 16
OKHttp是一个由Square Inc.开发的轻量级、高效的网络库,用于Android和Java平台。它提供了一种简单的方式来发送HTTP请求并处理响应。如果你想要通过OKHttp在网上抓取图片(也称为“下载图片”),你可以按照以下步骤操作:
1. 首先,确保你已经在项目中添加了OkHttp依赖。对于Gradle,可以在build.gradle文件中添加:
```groovy
implementation 'com.squareup.okhttp3:okhttp:4.x.y'
```
2. 创建一个OkHttpClient实例:
```java
OkHttpClient client = new OkHttpClient();
```
3. 编写一个函数来下载图片,例如使用`Request`对象来指定URL:
```java
public void downloadImage(String imageUrl, String destinationPath) throws IOException {
Request request = new Request.Builder()
.url(imageUrl)
.header("User-Agent", "Your User Agent") // 添加合适的用户代理
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
try (ResponseBody body = response.body()) {
byte[] imageBytes = body.readByteStream().toByteArray();
File file = new File(destinationPath);
Files.write(file.toPath(), imageBytes);
}
}
```
4. 调用这个函数,传入你要抓取的图片URL和保存路径:
```java
String imageUrl = "https://example.com/image.jpg";
String savePath = "/path/to/save/image.jpg";
downloadImage(imageUrl, savePath);
```
阅读全文
相关推荐

















