如何从远程Http服务器使用Java Socket下载映像? [英] How to download an image using Java Socket from a remote Http server?

查看:119
本文介绍了如何从远程Http服务器使用Java Socket下载映像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用Java Socket实现一个简单的http客户端。在我的程序中,我从服务器请求图像并尝试在本地计算机上复制请求的JPEG图像。我已设法构建请求并收到所需的内容。我还将响应头和内容分开了。但问题是当我使用 FileOutputStream 将字节写入.jpeg文件时,在写入图像查看器(如picasa)中打开文件后,图像似乎无效。
这是我的整个代码。
任何人都可以告诉我代码有什么问题吗?为什么图像无效?

I have been trying to implement a simple http client using Java Socket. In my program I am requesting an Image from a server and trying to copy the requested JPEG image on local machine. I have managed to construct the request and received the desired content. I have also separated the response header and the content. But the problem is when I write the bytes using FileOutputStream into a .jpeg file and after writing when open the file in a image viewer (like picasa) the image seems to be invalid. Here is my entire code. Can anyone plz tell me what's wrong with code? Why the image is invalid?

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);
    }

}  


推荐答案

请先尝试以下工作代码:

Please try this working code first:

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLTest {

  private static void sendGet() throws Exception {

    String url = "http://www.uni-koblenz-landau.de/images/starts-c-ko.jpg";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    InputStream in = con.getInputStream();
    OutputStream out = new FileOutputStream("/Users/ravikiran/Desktop/abc.jpg");
    try {
      byte[] bytes = new byte[2048];
      int length;

      while ((length = in.read(bytes)) != -1) {
        out.write(bytes, 0, length);
      }
    } finally {
      in.close();
      out.close();
    }
  }

  public static void main(String[] args) throws Exception {
    sendGet();
  }
}

这篇关于如何从远程Http服务器使用Java Socket下载映像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆