gpt4 book ai didi

java - 如何从网络服务器检索图像(image/png header)

转载 作者:行者123 更新时间:2023-12-01 18:46:40 24 4
gpt4 key购买 nike

我有一个带有 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());
}

感谢您的回复。

最佳答案

试试这个:

public static void saveImage(String imageUrl, String destinationFile) throws IOException {

URL url = new URL(imageUrl);
try(InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile)){

byte[] b = new byte[2048];
int length;

while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}

}catch(IOException e){
throw e;
}
}

Getting Image from URL (Java)

关于java - 如何从网络服务器检索图像(image/png header),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com