java - 如何在java中为图像创建http响应?
问题描述
我一直在尝试创建一个简单的 java web 服务器,对于 html 或 css 等文件,一切正常,但我无法正确发送图像响应。问题显然出在我发送的图像数据上,但我不确定如何正确处理。我一直在寻找有关它的任何信息很长一段时间没有,我只是找不到任何有用的东西可以解决我的问题。
我的部分代码:
public void Send(String path) throws IOException {
File file = new File(path);
if(file.exists()) {
if(!file.isDirectory()) {
if(isImage(file)) {
InputStream is = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(is);
String response = "HTTP/1.1 200 OK" + CRLF + "Content-Length: " + bytes.length + CRLF;
response += "content-type: image/jpeg" + CRLF + CRLF;
outputStream.write(response.getBytes());
outputStream.write(bytes);
outputStream.write((CRLF + CRLF).getBytes());
outputStream.flush();
} else {
String data = "";
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
data += st;
}
int length = data.getBytes().length;
String response = "HTTP/1.1 200 OK" + CRLF + "Content-Length: " + length + CRLF;
response += CRLF + data + CRLF + CRLF;
br.close();
outputStream.write(response.getBytes());
}
return;
}
}
SendError("404 Not Found");
}
outputStream 是来自 Socket 的 OutputStream。
我看到了这一点,但我认为我至少只在图像部分使用流。
我是新手,所以任何帮助将不胜感激!
编辑(更多信息):
浏览器信息:
isImage(file) 方法工作正常,我已经测试过了,但这里是:
private boolean isImage(File file) {
String mimetype = new MimetypesFileTypeMap().getContentType(file);
String type = mimetype.split("/")[0];
return type.equals("image");
}
图像是2.jpg
编辑 2
我编写了这段代码来将数组的内容写入文本文件:
String out = "";
for(int i = 0; i < bytes.length; i++) {
if(i%16 == 0) {
out += "\n";
}
out += String.format("%02X ", bytes[i]);
}
BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"));
writer.write(out);
writer.close();
所以我检查了图像和数组的开头,它们似乎是相同的。
之后我尝试创建一个客户端进行测试:
private static void Get2(String link) throws IOException {
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.68");
con.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
con.setRequestProperty("Sec-Fetch-Site", "same-origin");
con.setRequestProperty("Sec-Fetch-Mode", "no-cors");
con.setRequestProperty("Sec-Fetch-Dest", "image");
con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
con.setRequestProperty("Accept-Language", "sl,en;q=0.9,en-GB;q=0.8,en-US;q=0.7");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setInstanceFollowRedirects(false);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
int i = 0;
while ((inputLine = in.readLine()) != null) {
if(i < 5) {
System.out.println(inputLine);
} else {
content.append(inputLine);
}
i++;
}
in.close();
con.disconnect();
BufferedWriter writer = new BufferedWriter(new FileWriter("test2.txt"));
writer.write(content.toString());
writer.close();
}
我调用了函数:Get2("http://localhost:8080/images/2.jpg");
并在 test2.txt 中保存了数据。在里面我看到了类似数据的一些部分,但它显然有问题。我不确定我是否错误地使用了这个客户端测试,所以如果我做错了什么或者应该使用其他东西,请告诉我。
感谢所有愿意并且已经提供帮助或有任何建议的人。
解决方案
我终于弄明白了。实际上,我不提供一切都是不好的。
字符串 CRLF = "\n\r";
但显然,它应该只是\n。
我在某处读到 Windows 在 \n 之后自动添加 \r。我不知道这是否属实,但删除 \r 解决了我的问题,因为我之后有 2 个空行,GET / HTTP/1.1
因此其他内容被视为数据的一部分。
一旦我改变了一切正常。再次感谢您的帮助!
编辑
没关系。我做错的是\n和\r的顺序。应该\r\n
不是\n\r
推荐阅读
- html - 将鼠标悬停在父 div 上时 CSS 淡化子元素,然后将鼠标悬停在子元素上时再次更改
- vue.js - 从另一个模块访问 vuex 模块状态
- python - 如何将我的 Google Blogger 文件导入 Pelican 而不会出错?
- hyperledger - 超级账本节点的更好做法是什么……?
- ios - iOS 以编程方式获取 Eve Motion 传感器状态
- ios - 从 pod 安装框架后,无法在 Swift 项目的类中导入,抛出错误 no such module swift import
- html - Google 表格公式中的 ImportXml Xpath
- javascript - Nativescript Vue.js 定位 GPS
- phpmyadmin - phpMyAdmin 4.8.4 身份验证应用程序 (2FA)
- javascript - 将纯文本值的行加载到字符串数组中