0

I wrote a program in java to check what a browser send to http sever. The program noted the following texts( let name it TEXT_BROWSER)

GET / HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive

Now I made another program which send the "TEXT_BROWSER" to any website(google,my router(192.168.1.1)) but I got no response(no text from the server) I want to know what is the error in my program.

My java program

//1streqbybrowser.txt contains TEXT_BROWSER<br/>
import java.net.*;
import java.io.*;
class TCPClient 
{
 public static void main(String argv[]) throws Exception
 {
  String sentence;
  File f=new File("1streqbybrowser.txt");
  FileReader fr=new FileReader(f);
  BufferedReader br=new BufferedReader(fr);  
  Socket clientSocket = new Socket("192.168.1.1", 80);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  while((sentence = br.readLine())!=null)
   outToServer.writeBytes(sentence+"\n");
  System.out.println("Sending finished");
  while((sentence = inFromServer.readLine())!=null)
    System.out.println(sentence);
  clientSocket.close();
 }
}

EDIT

I changed 2nd line of TEXT_BROWSER from Host: localhost toHost: 192.168.1.10 to send to my router(192.168.1.1), still not got any response from it
EDIT AGAIN
I did changes as mentioned by @andremoniy but only ast line of TEXT_BROWSER is sent to server and something received, 2nd loop does not end

>GET / HTTP/1.1
< HTTP/1.1 400 Bad Request
< Content-Length: 0
< Server: RomPager/4.07 UPnP/1.0
< EXT:
<

I noticed that inner loop never ends here.
Now what could be the reason?

Gaurav Sharma
  • 745
  • 7
  • 23
  • Possibly duplicate of: http://stackoverflow.com/questions/9959573/simple-java-http-client-no-server-response – Andremoniy Jan 11 '13 at 18:10

1 Answers1

0

Modify your program in part of while loop like that:

    while ((sentence = br.readLine()) != null) {
        outToServer.writeBytes(sentence + "\r\n\r\n");
        outToServer.flush();
        System.out.println(">" + sentence);
        while ((sentence = inFromServer.readLine()) != null)
            System.out.println("< " + sentence);
    }

And you will see the result.

The main cause of your fail is 3 things:

1) you should use \r\n after each line

2) I you have to flush writer after each line

3) read server answer after each sent line

Andremoniy
  • 34,031
  • 20
  • 135
  • 241