Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am successfully using this code to send HTTP requests with some parameters via GET method

function void sendRequest(String request)
{
    // i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=c";
    URL url = new URL(request); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
    connection.setDoOutput(true); 
    connection.setInstanceFollowRedirects(false); 
    connection.setRequestMethod("GET"); 
    connection.setRequestProperty("Content-Type", "text/plain"); 
    connection.setRequestProperty("charset", "utf-8");
    connection.connect();
}

Now I may need to send the parameters (i.e. param1, param2, param3) via POST method because they are very long. I was thinking to add an extra parameter to that method (i.e. String httpMethod).

How can I change the code above as little as possible to be able to send paramters either via GET or POSt?

I was hoping that changing

connection.setRequestMethod("GET");

to

connection.setRequestMethod("POST");

would have done the trick, but the parameters are still sent via GET method.

Has HttpURLConnection got any method that would help? Is there any helpful Java construct?

Any help would be very much appreciated.

Thanks,
Dan

share|improve this question
Post parameters are sent inside the http header section not in the URL. (your post url would be http://example.com/index.php) – dacwe Nov 17 '10 at 15:34
1  
there is no method setRequestMethod in Java 1.6 defined: docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html – ante.sabo Jul 5 '12 at 11:24
1  
Cast it to Http(s)UrlConnection .... – Peter Kriens Jul 9 '12 at 14:52

3 Answers

up vote 78 down vote accepted

In a GET request, the parameters are sent as part of the URL.

In a POST request, the parameters are sent as a body of the request, after the headers.

To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

This code should get you started:

String urlParameters = "param1=a&param2=b&param3=c";
String request = "http://example.com/index.php";
URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
share|improve this answer
1  
Hi Alan. In your code there is no call to connect(). Is that right? – dan Nov 17 '10 at 15:44
That's right, url.openConnection() opens the connection for us already, so we just need to write to it. – Alan Geleynse Nov 17 '10 at 15:49
9  
@Alan Geleynse : 'url.openconnection()' does not open connection. In case you do not specify a connect() statement the connection is opened when you write to to the http request body /heared and send it. I have tried this with certificates. The ssl handshake takes place only after you call connect or when you send a data to the server. – Ashwin Mar 23 '12 at 10:20
5  
getBytes() uses default charaset of environment, NOT UTF-8 charset=utf-8 must follw the content type: application/x-www-form-urlencoded;charset=utf-8 You do byte conversion twice in the example. Should do: byte[] data = urlParameters.getData("UTF-8"); connection.getOutputStream().write(data); no use to close AND flush AND disconnect – Peter Kriens Jul 9 '12 at 15:00
1  
@PeterKriens Thanks for your addition -- I believe you meant byte[] data = urlParameters.getBytes(Charset.forName("UTF-8")) :). – gerrytan Apr 15 at 23:52
show 4 more comments

I couldn't get Alans example to actually do the post, so I ended up with this:

String urlParameters = "param1=a&param2=b&param3=c";
URL url = new URL("http://example.com/index.php");
URLConnection conn = url.openConnection();

conn.setDoOutput(true);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(urlParameters);
writer.flush();

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}
writer.close();
reader.close();         
share|improve this answer
nice one - reading the response in while – kommradHomer May 28 at 13:16

I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.

That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.