I want to find the size of an HTML file without HTTP headers and data transfer rate. Below is my code;
import java.net.*;
import java.io.*;
public class HttpCon
{
public static void main ( String[] args ) throws IOException
{
Socket s = null;
try
{
String host = "host1";
String file = "file1";
int port = 80;
s = new Socket(host, port);
OutputStream out = s.getOutputStream();
PrintWriter outw = new PrintWriter(out, false);
outw.print("GET " + file + " HTTP/1.1\r\n");
outw.print("Host: " + host + ":" + port + "\r\n");
outw.print("Accept: text/plain, text/html, text/*\r\n");
outw.print("\r\n");
outw.flush();
InputStream in = s.getInputStream();
InputStreamReader inr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inr);
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
br.close();
}
}
}
But I do not have any idea how to do this. Is there a source code that I can look at or any resource that I can apply?
Any help will be appreciated, thanks in advance.
What you are asking for shouldn’t be much of a problem. Read the lines until you read an empty line — that’s where the headers end. After that just go on reading and count all the characters you have read and that’s your file size. As for transfer rate:
The only problem here will be that you are using a
BufferedReaderso you count chars and not bytes. If you need bytes, then you’ll need to use the rawInputStreamand then it’s going to be a slight pain in the butt to find where the headers end. You can get around that (probably) by using not theBufferedReaderbut theInputStreamReader, which will not read-ahead anything. When you find the end of headers, switch to the rawInputStreamto read the response body.