简体   繁体   中英

sending request to server using socket in java

I'm using socket to establish a streaming connection with server. By creating a socket, I tried to send a request to the server using the socket. but the request isn't received by server no matter which method I use. these are the methods I used to send request.

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(query);

or the other one is

 out = new ObjectOutputStream(connection.getOutputStream());
 out.writeObject(msg);
 out.flush();

the request I'm trying to send is something like this:

String query = String.format("cmd=%s&version=%s", "handshake", "1.0");

I know that sending this query is much easier by using Httpconnection, but this is the way that it has to be done. so please help me with this. this is the httpconnection commands

 String charset = "UTF-8";
 String query = String.format("cmd=%s&version=%s", "handshake", "1.0");
 String charset = "UTF-8";
 URL url = new URL("serveraddress:8080");           
 URLConnection conn = url.openConnection();         
 conn.setDoOutput(true);            
 conn.connect();            
 OutputStream output = conn.getOutputStream();              
 output.write(command.getBytes(charset));                                       

 InputStreamReader content = new InputStreamReader(conn.getInputStream());                              
 String result ="";
 int c = content.read();
 while (c != -1) {
    result = result + ((char) c);  
        c = content.read();
} 
 Log.v(logTag, "Received: [" + result + "]");

and this is what I did in socket which didn't work

 URL url = new URL("serveraddress:8080");               
 String server_name = url.getHost();
 int port = url.getPort();
 Socket socket = new Socket(server_name, port);                         

 String query = "post /swarm HTTP/1.1\nHost: serveraddress\n" +
 "content-length: 27\nkeep-alive: 300\nconnection: keep-alive\n\n" +
 "cmd=handshake&version=1.0\n"; 

 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
 out.println(query);

according to the server log the socket connection opened and closed without getting any request

The three methods you mention (PrintWriter, ObjectOutputStream and HTTPConnection) will all result in something being sent to the server, but what is actually sent will differ greatly between the various methods.

First of all, the Java ObjectOutputStream class will encode the objects that you write to it along with information about the classes that these objects are instances of, especially class names, signatures etc. This is practically only appropriate when you are communicating with another Java application that is using an ObjectInputStream on the other end to read it. It will especially not adhere to the HTTP protocol and as such you would most likely not be able to use it at all with anything that you can use an HTTPConnection to.

Using a HttpURLConnection will actually construct and send complete (and most importantly, valid) HTTP requests to the server you are trying to connect to. For example, if you were to execute the following code:

URL url = new URL("http://localhost/test?cmd=handshake&version=1.0");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

Then the result will be that your application connects to localhost:80 and writes something like the following: (This is a simplified request. There will be additional headers and information in the actual request.)

GET /test?cmd=handshake&version=1.0 HTTP/1.1
Host: localhost

Finally, if you are using a PrintWriter then that will actually send pure text to the server. However, if the server is a HTTP server, which is likely since you say it responds to the HTTP connection, then it is not enough just to send the command part of the request. You will have to send the rest as well, including the GET , the HTTP version, maybe some headers, the trailing empty lines and the CRLF line endings. This can all be done using a PrintWriter.

It could be a good idea to install a network packet analyzer such as Wireshark and use it to actually see what is sent to the server when you perform your connection using a httpconnection and then trying to mimic that by manually constructing the request.

I would also recommend reading up on some more details regarding the HTTP protocol. A good starting point can be the Wikipedia article .

Edit based on new information in the OP:

There are some small inconsistencies in the updated code, some of which I can assume is copy-paste mistakes, others that I would like to point out just in case.

The solution based on a URLConnection does not specify the "/swarm" resource anywhere. Adding that will not change whether a request is actually sent or not, or even if its valid or not, but it could affect whether you can find the request in the logs or not.

The query string does overall look reasonable with the exception that POST is written using lowercase letters. At first I didn't think that this would make any difference, but when trying "get" vs. "GET" against www.google.com over Telnet, it DOES seem to make a difference. If the web server doesn't recognize the request as a request then it won't be able to process it and thus it might not show up in the logs as you expect.

I would recommend that you actually read the server response and print it to System.out so that you see if the server is reporting any particular error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM