【发布时间】:2020-01-20 12:17:16
【问题描述】:
我有一个带有 PHP 脚本的 Web 服务器,它为我提供了存储在服务器上的随机图像。此响应直接是具有以下标头的图像:
HTTP/1.1 200 OK
Date: Mon, 20 Jan 2020 12:10:05 GMT
Server: Apache/2.4.29 (Ubuntu)
Expires: Mon, 1 Jan 2099 00:00:00 GMT
Last-Modified: Mon, 20 Jan 2020 12:10:05 GMT
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 971646
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: image/png
如您所见,服务器使用 MIME png 文件类型直接回复我。现在我想从一个 JAVA 程序中检索这个图像。我已经有一个代码可以让我从 http 请求中读取文本,但是如何保存来自网络的图像?
public class test {
// one instance, reuse
private final HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
public static void main(String[] args) throws Exception {
test obj = new test();
System.out.println("Testing 1 - Send Http POST request");
obj.sendPost();
}
private void sendPost() throws Exception {
// form parameters
Map<Object, Object> data = new HashMap<>();
data.put("arg", "value");
HttpRequest request = HttpRequest.newBuilder()
.POST(buildFormDataFromMap(data))
.uri(URI.create("url_here"))
.setHeader("User-Agent", "Java 11 HttpClient Bot") // add request header
.header("Content-Type", "application/x-www-form-urlencoded")
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.headers());
try {
saveImage(response.body(), "path/to/file.png");
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void saveImage(String image, String destinationFile) throws IOException {
//What to write here ?
}
private static HttpRequest.BodyPublisher buildFormDataFromMap(Map<Object, Object> data) {
var builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if (builder.length() > 0) {
builder.append("&");
}
builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
}
return HttpRequest.BodyPublishers.ofString(builder.toString());
}
感谢您的回复。
【问题讨论】:
-
只是一个 2c,但除非服务器将图像作为 Base64 编码字符串发送,否则最简单的方法是将图像作为字节数组读取,然后将其写入文件。
-
使用输入流下载任何文件类型,更多参考url
-
非常感谢@Nazimch 你解决了我的问题
标签: java