【发布时间】:2016-04-12 06:28:30
【问题描述】:
这个程序应该从flicker下载指定的图像。这是一个家庭作业问题,我必须使用套接字。我的程序成功发出 http 请求并收到响应。我消除了标题并将字节写入 jpg 文件。但是当我想用图像查看器程序打开它时,它会说:
解释 JPEG 图像文件时出错(在 状态 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");
}
}
【问题讨论】:
-
您不能假设整个
\r\n\r\n序列在一次读取中到达,当然也不能将String用作二进制数据的容器。我会先阅读所有标题行,然后开始复制循环。 -
当我打印 indexOfEOH 和长度时(如果您运行代码,它会打印它们),对我来说似乎没问题。我的意思是它建立了索引。否则它不应该进入内部,对吧?我应该如何阅读标题行以确保我到达 \r\n\r\n?
-
使用
DataInputStream.readLine(),是的,我知道它已被弃用。 -
你是对的,它成功了!非常感谢,你在最后一刻救了我:)
标签: java sockets character-encoding jpeg