我一直在试图实现使用Java Socket实现简单的HTTP客户端。 在我的计划,我从服务器请求的图像,并试图请求的JPEG图像复制本地机器上。 我已成功地构建了请求和接收到的期望的内容。 我还分离出的响应报头和内容。 但问题是,当我写的使用字节FileOutputStream
为.jpeg文件,写打开的图像浏览器(例如Picasa)文件时,图像似乎无效后。 这是我的全部代码。 任何人都可以PLZ告诉我,什么是错的代码? 为什么像无效?
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import sun.misc.IOUtils;
public class ImageCopy {
public static void main(String args[]) throws IOException{
String host = "www.uni-koblenz-landau.de"; //declare the host name
String resourceLoc = "/images/starts-c-ko.jpg"; //declare the specific pagename of get
HttpRequester req = new HttpRequester();
req.request(host, resourceLoc); //send the request mentiong the host and pagename
}
}
class HttpRequester{
public void request(String host, String resourceLoc) throws IOException{
Socket httpSocket = new Socket(host, 80); //create the request for port 80
PrintWriter writer = new PrintWriter(httpSocket.getOutputStream());
FileOutputStream foutStream = new FileOutputStream("E:\\quora.jpeg"); //creating file to hold the output stream
// building the header fields
String protocol = "GET /" +resourceLoc+" HTTP/1.1";
String connection ="Connection: close";
String acceptedLanguage ="Accept-Language: de,en;q=0.7,en-us;q=0.3";
String headerEnd = "";
String HostHeader = "Host: www.uni-koblenz-landau.de";
// writing the headers to the outputstream
writer.println(protocol);
writer.println(HostHeader);
writer.println(connection);
writer.println(acceptedLanguage);
writer.println(headerEnd);
writer.flush();
// request sent
BufferedInputStream reader = new BufferedInputStream(httpSocket.getInputStream());
InputStream is;
int byteCode =0;
char ch ;
StringBuilder builder = new StringBuilder();
while((byteCode=reader.read())!=-1)
{
builder.append((char)byteCode);
// System.out.print((char)byteCode);
}
String text = builder.toString();
// sub[0] is supposed to contain the header and sub[1] should contain the bytes of the image
String[] sub = text.split("\r\n\r\n");
System.out.println(sub[0]);
byte[] byts = sub[1].getBytes();
for(int i=0;i<byts.length;i++){
foutStream.write(byteCode);
}
System.out.println(byts.length);
}
}