这个程序应该从闪烁下载指定的图像。这是一个家庭作业问题,我必须使用套接字。我的程序成功地发出http请求并接收响应。我消除了标题,并将字节写入jpg文件。但是,当我想用图像查看程序打开它时,它说:
解释JPEG图像文件时出错(在状态200中不正确地调用JPEG库)
所以我下载了图像,然后在一个文本编辑器中打开,它的某些部分似乎没有被转换。
原始档案:
\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");
}}
发布于 2016-04-11 22:28:30
在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();
} https://stackoverflow.com/questions/36558857
复制相似问题