Я пытался реализовать простой клиент http с помощью Java Socket. В моей программе я запрашиваю изображение с сервера и пытаюсь скопировать требуемый образ JPEG на локальный компьютер. Мне удалось создать запрос и получить желаемый контент. Я также разделил заголовок ответа и содержимое. Но проблема в том, что я пишу байты с использованием FileOutputStream
в файл .jpeg, и после записи, когда вы открываете файл в средстве просмотра изображений (например, picasa), изображение кажется недействительным. Вот мой весь код. Может ли кто-нибудь рассказать мне, что не так с кодом? Почему изображение недействительно?Как загрузить изображение с помощью Java Socket с удаленного сервера Http?
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);
}
}
, вероятно, не ошибка, но вы не закрывающие foutStream. – SteveL
Зачем использовать гнездо? Почему бы не HttpURLConnection? – EJP