Sending a POST Request Using a URL

See also Sending a POST Request Using a Socket.
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"); // Send data URL url = new URL("http://hostname:80/cgi"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { // Process line... } wr.close(); rd.close(); } catch (Exception e) { }

Comments

14 Feb 2010 - 7:47pm by geeks-online.de (not verified)

Ich glaube der Key darf nicht UrlEncoded werden ?!?

Bitte um Rückmeldung.

16 Feb 2010 - 5:49am by Anonymous (not verified)

Hey it saved a lot of time. Thanks

16 Feb 2010 - 8:22am by Xandl (not verified)

hey geeks-online.de ... what about keys that go: ab?c or a&b or even a=b ?? they would break everything

23 Feb 2010 - 8:22am by Anonymous (not verified)

I think this is the get method, not post

1 Mar 2010 - 6:44am by Anonymous (not verified)

no, it's the POST. In POST, parameters are written in the outputstream, in GET, they are appended to the URL ("http://hostname:80/cgi?key1=value1&key2=value2")

3 Mar 2010 - 6:12am by Anonymous (not verified)

It will throw exception when the program excutes the statment " OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());"
How to fix it??

9 Mar 2010 - 11:50pm by Anonymous (not verified)

:)

9 Mar 2010 - 11:51pm by Anonymous (not verified)

good example/// :)

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.