gpt4 book ai didi

java - 通过java套接字下载图像时需要编码规范吗?

转载 作者:行者123 更新时间:2023-12-01 10:04:20 25 4
gpt4 key购买 nike

该程序应该从闪烁中下载指定的图像。这是一个家庭作业问题,我必须使用套接字。我的程序成功发出 http 请求并收到响应。我消除了 header 并将字节写入 jpg 文件。但是当我想用图像查看器程序打开它时,它说:

Error interpreting JPEG image file(Improper call to JPEG library in state 200

所以我单独下载了图像并在文本编辑器中打开,看起来它的某些部分没有转换。

原始文件:

\FF\D8\FF\E0\00JFIF\00\00\00\00\00\00\FF\E2\A0ICC_PROFILE

下载的文件:

ᅵᅵᅵᅵ\00JFIF\00\00\00\00\00\00ᅵᅵᅵICC_PROFILE

这与字符编码有关吗?如果是,我应该如何指定编码?或者我应该怎么做才能真正获得jpeg文件?

public class ImageReceiver {
public static void main(String[] args) {
String imglink = "https://farm2.staticflickr.com/1495/26290635781_138da3fed8_m.jpg";
String flicker = "farm2.staticflickr.com";

Socket socket = null;
DataOutputStream out;

try {
socket = new Socket(flicker, 80);
out = new DataOutputStream(socket.getOutputStream());

out.writeBytes("GET "+ imglink +" HTTP/1.1\r\n");
out.writeBytes("Host: "+ flicker +":80\r\n\r\n");
out.flush();
} catch (IOException e) {
e.printStackTrace();
}

DataInputStream in = null;
OutputStream output = null;

try {
in = new DataInputStream(socket.getInputStream());
output = new FileOutputStream("chair.txt");

System.out.println("input connection is established");

byte[] bytes = new byte[2048];
int length;
boolean eohFound = false;

while ((length = in.read(bytes)) != -1) {
if(!eohFound){
String string = new String(bytes, 0, length);
int indexOfEOH = string.indexOf("\r\n\r\n");
if(indexOfEOH != -1) {
System.out.println("index: " + indexOfEOH);
length = length - indexOfEOH - 4;
System.out.println(length);
bytes = string.substring(indexOfEOH + 4).getBytes();
eohFound = true;
} else {
length = 0;
}
}
output.write(bytes, 0, length);
output.flush();
}
} catch (IOException e) {
e.printStackTrace();
}


try {
in.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("Image is downloaded");

}

}

最佳答案

在EJP的帮助下,我重写了我的代码。这里只修改了部分。我 readLine() 直到得到新行,然后我读取字节并写入文件:

    try {
in = new DataInputStream(socket.getInputStream());
output = new FileOutputStream("chair.jpg");

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

String inputLine;

//Get rid of headers...
while ((inputLine = in.readLine()) != null){
if(inputLine.equals(""))
break;
}


while ((length = in.read(bytes)) != -1) {
output.write(bytes, 0, length);
output.flush();
}

} catch (IOException e) {
e.printStackTrace();
}

关于java - 通过java套接字下载图像时需要编码规范吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558857/

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