Reputation:
I'm forced to used TCP sockets for this.
I need to query some ip, get an image from it and put it in a file.
so my actual code looks like this :
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();
And I get the following error :
java.lang.IllegalArgumentException: image == null!
I was previously reading manually all bytes. I'm getting the picture, but there is some bytes missing (around 7000) at the beginning.
How to get it to work?
Upvotes: 1
Views: 1255
Reputation:
So it appears the problem is the following :
Using two reader on the InputReader is not safe. The first read might consume some data even if you don't explicitely call read on it. It will keep it's buffer full.
So the solution is simply to use the same ready for both.
I fixed it by removing the header using a byte reader. I could after use this byte reader to obtain my picture.
Upvotes: 1
Reputation: 310860
Don't use Socket for this, use URL and HttpURLConnection: that's what they're for. There is at least one HTTP protocol error in your code, probably benign, but it wouldn't be there if you were using the right class
Doing that would also get rid of the BufferedReader which you are using to read past the headers, and which is causing this problem, by reading ahead and buffering part of the image.
Upvotes: 0