我被迫为此使用 TCP 套接字。
我需要查询一些 ip,从中获取图像并将其放入文件中。
所以我的实际代码如下所示:
InetAddress ip = InetAddress.getByAddress(rawip);
Socket socket = new Socket(ip, 80);
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println("GET "+ url +" HTTP/1.1");
pw.println("Host: " + m_url.substring(4));
pw.println("Connection: Close");
pw.println("User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36");
pw.println("");
pw.flush();
BufferedReader in = new BufferedReader(new InputStreamReader (socket.getInputStream()), 1);
String ln;
//Reading header
while((ln = in.readLine()) != null)
{
//if header is finished
if (ln.equals("")) break;
}
BufferedImage imgage = ImageIO.read(socket.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( imgage, format, baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
我收到以下错误:
java.lang.IllegalArgumentException: image == null!
我以前手动读取所有字节。我得到了图片,但开头缺少一些字节(大约 7000)。
如何让它工作?