Sending a POST Request Using a Socket

See also Sending a POST Request Using a URL.
try { // Construct data String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); // Create a socket to the host String hostname = "hostname.com"; int port = 80; InetAddress addr = InetAddress.getByName(hostname); Socket socket = new Socket(addr, port); // Send header String path = "/servlet/SomeServlet"; BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")); wr.write("POST "+path+" HTTP/1.0\r\n"); wr.write("Content-Length: "+data.length()+"\r\n"); wr.write("Content-Type: application/x-www-form-urlencoded\r\n"); wr.write("\r\n"); // Send data wr.write(data); wr.flush(); // Get response BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; while ((line = rd.readLine()) != null) { // Process line... } wr.close(); rd.close(); } catch (Exception e) { }

Comments

19 Jan 2010 - 4:09am by cristobal (not verified)

something is wrong in your code:
it's not : Socket socket = new Socket(addr, port);
it's : Socket socket = new Socket(hostname , port);

19 Jan 2010 - 7:00am by patrick

Actually, the Socket API takes both forms.

18 Feb 2010 - 12:41am by Zahid Hussain (not verified)

Thanks It Works :)

24 Feb 2010 - 12:23pm by Rushil (not verified)

hey if u wanna send the data to a PARTICULAR FIELD in the URL, that is, the webpage, then how do u do that?

8 Mar 2010 - 9:16am by Anonymous (not verified)

Throws 400 Bad Request Error!

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.