该程序应从闪烁下载指定的图像。这是一个作业问题,我必须使用套接字。我的程序成功发出了http请求并收到了响应。我消除了标头并将字节写入jpg文件。但是,当我想使用图像查看器程序打开它时,它说:
解释JPEG图像文件时出错(对JPEG库的调用不正确
状态200
因此,我分别下载了该图像并在文本编辑器中将其打开,似乎其中的某些部分未转换。
原始文件:
\ FF \ D8 \ FF \ E0 \ 00 JFIF \ 00 \ 00 \ 00 \ 00 \ 00 \ 00 \ FF \ E2 \ A0ICC_PROFILE
下载文件:
\ 00 JFIF \ 00 \ 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的帮助下,我重新编写了代码。这里只修改了一部分。我先读Line()直到得到新行,然后再读取为字节并写入文件:
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/