Use of java.net.URLConnection
is asked about pretty often here, and the Oracle tutorial is too concise about it.
That tutorial basically only shows how to fire a GET request and read the response. It doesn't explain anywhere how to use it to among others perform a POST request, set request headers, read response headers, deal with cookies, submit a HTML form, upload a file, etc.
So, how can I use java.net.URLConnection
to fire and handle "advanced" HTTP requests?
Inspired by this and other questions on SO, I've created a minimal open source basic-http-client that embodies most of the techniques found here.
google-http-java-client is also a great open source resource.
I was also very inspired by this response.
I am often on projects where I need to do some HTTP, and I may not want to bring in a lot of 3rd party dependencies (which bring in others and so on and so on, etc.)
I started to write my own utilities based on some of this conversation (not any where done):
Then there are just a bunch or static methods.
Then post...
Well you get the idea....
Here are the tests:
You can find the rest here:
https://github.com/RichardHightower/boon
My goal is to provide the common things one would want to do in a bit more easier way then....
You can also use
JdkRequest
from jcabi-http (I'm a developer), which does all this work for you, decorating HttpURLConnection, firing HTTP requests and parsing responses, for example:Check this blog post for more info: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html
When working with HTTP it's almost always more useful to refer to
HttpURLConnection
rather than the base classURLConnection
(sinceURLConnection
is an abstract class when you ask forURLConnection.openConnection()
on a HTTP URL that's what you'll get back anyway).Then you can instead of relying on
URLConnection#setDoOutput(true)
to implicitly set the request method to POST instead dohttpURLConnection.setRequestMethod("POST")
which some might find more natural (and which also allows you to specify other request methods such as PUT, DELETE, ...).It also provides useful HTTP constants so you can do:
Update
In Java 9, you can send a
GET
request like:Then you can examine the returned
HttpResponse
:Since this new HTTP Client is in
java.httpclient
jdk.incubator.httpclient
module, you should declare this dependency in yourmodule-info.java
file: