In Java, How to compose an HTTP request message and send it to an HTTP web server?
-
33[There's a mini tutorial here at SO](http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests). – BalusC Oct 18 '10 at 12:56
-
http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html In particular, getHeaderField, getHeaderFieldKey, and getContent – Federico klez Culloca Aug 31 '09 at 22:37
-
You could use the JSoup lib (http://jsoup.org) . It does exactly what you ask! Document doc = Jsoup.connect("http://en.wikipedia.org"). get(); (from the site). A more pythonic way for java. – user2007447 Jul 26 '15 at 13:12
10 Answers
You can use java.net.HttpUrlConnection.
Example (from here), with improvements. Included in case of link rot:
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
-
2Here is another nice code snippet in replace for Java Almanac: [HttpUrlConnection-Example](http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139) – GreenTurtle Dec 14 '12 at 12:15
-
25
-
3Since Java 9, creating HTTP request [has become much easier](https://www.baeldung.com/java-http-request). – Anton Sorokin Jun 28 '19 at 12:43
-
Yes, a lot has changed in the ten years since this answer was given. Not everyone has moved on from JDK8 to 9 and beyond. – duffymo Jun 28 '19 at 12:44
-
How to put some header content in the request with this way of doing, please ? – nonozor Sep 20 '22 at 14:00
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
-
1The strange thing is that some servers will reply you back with strange ? characters (which seems like an encoding error related to request headers but not) if you don't open an output stream and flush it first. I have no idea why this happens but will be great if someone can explain why? – Gorky Jan 18 '13 at 08:33
-
1
-
101This is way too much line noise to send an HTTP request imo. Contrast to Python's requests library: `response = requests.get('http://www.yahoo.com/')`; something of similar brevity should be possible in Java. – Dan Passaro Jul 12 '14 at 19:09
-
24@leo-the-manic that's because Java is supposed to be a lower level language (than python) and allows (forces) the programmer to handle the details underneath rather than assuming "sane" defaults (i.e. buffering, character encoding, etc.). It is possible to get something as succinct, but then you lose lots of the flexibility of the more barebones approach. – fortran Feb 17 '15 at 23:54
-
1@leo-the-manic If there is no such thing as you look for, do go and write by yourself. I do that all the time and I do have quick get/post static methods on both java and C# – Felype Jul 28 '15 at 13:05
-
14@fortran Python has equally low-level options to accomplish the same thing as above. – User Mar 18 '17 at 04:46
-
That's exactly why Java is stopped being thought in schools. Relic of the history. – Ska Sep 28 '17 at 12:03
-
@fortran Java is not 'lower level' than Python... how does that make any sense? – DanGordon Sep 29 '17 at 18:41
-
What Dan Passaro is saying is there should be a wrapper for all that code. And the wrapper should be part of the Plain Old Java Objects. So he (and me) don't need to worry about all of the under-the-hood mechanics. That would be a class that has, as input, the URL, and as output, the String [] array. or just one long string. – Baruch Atta Jun 28 '18 at 16:00
-
my wrapper: // import java.net.*; // import java.io.*; public static String getWebPage(String targetURL) { String s = "", t = ""; URL url = null; URLConnection connection = null; try { url = new URL(targetURL); connection = url.openConnection(); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader( connection.getInputStream())); while ((t = in.readLine()) != null) { s = s + "\n" + t; } in.close(); } catch (IOException e) { e.printStackTrace(); } return s; } – Baruch Atta Jun 28 '18 at 16:35
I know others will recommend Apache's http-client, but it adds complexity (i.e., more things that can go wrong) that is rarely warranted. For a simple task, java.net.URL
will do.
URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
/* Now read the retrieved document from the stream. */
...
} finally {
is.close();
}

- 265,237
- 58
- 395
- 493
-
6That doesn't help if you want to monkey with request headers, something that's particularly useful when dealing with sites that will only respond a certain way to popular browsers. – Jherico Aug 31 '09 at 22:57
-
43You can monkey with request headers using URLConnection, but the poster doesn't ask for that; judging from the question, a simple answer is important. – erickson Sep 01 '09 at 03:26
Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.
Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.

- 4,744
- 8
- 33
- 64

- 76,006
- 17
- 150
- 174
-
3FWIW, our code started with java.net.HttpURLConnection, but when we had to add SSL and work around some of the weird use cases in our screwy internal networks, it became a real headache. Apache HttpComponents saved the day. Our project currently still uses an ugly hybrid, with a few dodgy adapters to convert java.net.URLs to the URIs HttpComponents uses. I refactor those out regularly. The only time HttpComponents code turned out significantly more complicated was for parsing dates from a header. But the [solution](http://stackoverflow.com/a/1930240/1450294) for that is still simple. – Michael Scheper Dec 13 '12 at 07:52
-
1
Here's a complete Java 7 program:
class GETHTTPResource {
public static void main(String[] args) throws Exception {
try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://example.com/").openStream())) {
System.out.println(s.useDelimiter("\\A").next());
}
}
}
The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.

- 20,267
- 14
- 135
- 196
-
@Ska There is no unhandled exception. `main()` throws Exception, which encompasses the MalformedURLException and the IOException. – jerzy Dec 22 '17 at 09:33
-
Scanner actually is not very optimized when it comes to performance. – WesternGun Mar 14 '19 at 14:44
This will help you. Don't forget to add the JAR HttpClient.jar
to the classpath.
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class MainSendRequest {
static String url =
"http://localhost:8080/HttpRequestSample/RequestSend.jsp";
public static void main(String[] args) {
//Instantiate an HttpClient
HttpClient client = new HttpClient();
//Instantiate a GET HTTP method
PostMethod method = new PostMethod(url);
method.setRequestHeader("Content-type",
"text/xml; charset=ISO-8859-1");
//Define name-value pairs to set into the QueryString
NameValuePair nvp1= new NameValuePair("firstName","fname");
NameValuePair nvp2= new NameValuePair("lastName","lname");
NameValuePair nvp3= new NameValuePair("email","email@email.com");
method.setQueryString(new NameValuePair[]{nvp1,nvp2,nvp3});
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
System.out.println("QueryString>>> "+method.getQueryString());
System.out.println("Status Text>>>"
+HttpStatus.getStatusText(statusCode));
//Get data as a String
System.out.println(method.getResponseBodyAsString());
//OR as a byte array
byte [] res = method.getResponseBody();
//write to file
FileOutputStream fos= new FileOutputStream("donepage.html");
fos.write(res);
//release connection
method.releaseConnection();
}
catch(IOException e) {
e.printStackTrace();
}
}
}

- 30,199
- 37
- 136
- 151

- 3,284
- 9
- 38
- 51
-
1Seriously, I really like Java, but what's the matter with that stupid `NameValuePair` list or array. Why not a simple `Map
`? So much boilerplate code for such simple use cases... – Joffrey Sep 03 '14 at 11:59 -
6@Joffrey Maps by definition have 1 key per value, means: `A map cannot contain duplicate keys` ! But HTTP Parameters can have duplicate keys. – Ben Dec 26 '16 at 20:47
Google java http client has nice API for http requests. You can easily add JSON support etc. Although for simple request it might be overkill.
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.io.InputStream;
public class Network {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
System.out.println(response.getStatusCode());
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
}

- 30,520
- 16
- 123
- 136
-
-
Sorry, that should have been `HTTP_TRANSPORT`, I've edited the answer. – Tombart Feb 10 '14 at 15:57
-
why is HttpResponse not AutoClosable? What is the difference from this and to working with Apache's CloseableHttpClient? – Janus Troelsen May 12 '16 at 23:57
-
The benefit is the API, which makes it personal preference really. Google's library uses Apache's library internally. That said, I like Google's lib. – Jeff Fairley Jun 24 '16 at 16:53
-
You may use Socket for this like
String host = "www.yourhost.com";
Socket socket = new Socket(host, 80);
String request = "GET / HTTP/1.0\r\n\r\n";
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();
InputStream is = socket.getInputStream();
int ch;
while( (ch=is.read())!= -1)
System.out.print((char)ch);
socket.close();

- 15,507
- 6
- 37
- 55

- 3,228
- 4
- 27
- 38
-
-
@CuriousGuy look at this link http://programmers.stackexchange.com/questions/29075/difference-between-n-and-r-n – laksys Sep 18 '16 at 01:16
-
3It seems to be even easier and more straight forward than the other solutions. Java makes things more complicated than it should be. – SwiftMango Jun 18 '18 at 14:11
There's a great link about sending a POST request here by Example Depot::
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) {
}
If you want to send a GET request you can modify the code slightly to suit your needs. Specifically you have to add the parameters inside the constructor of the URL. Then, also comment out this wr.write(data);
One thing that's not written and you should beware of, is the timeouts. Especially if you want to use it in WebServices you have to set timeouts, otherwise the above code will wait indefinitely or for a very long time at least and it's something presumably you don't want.
Timeouts are set like this conn.setReadTimeout(2000);
the input parameter is in milliseconds

- 310,957
- 84
- 592
- 636

- 963
- 10
- 10
If you are using Java 11 or newer (except on Android), instead of the legacy HttpUrlConnection class, you can use Java 11 new HTTP Client API.
An example GET request:
var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true");
var client = HttpClient.newHttpClient();
var request = HttpRequest
.newBuilder()
.uri(uri)
.header("accept", "application/json")
.GET()
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
The same request executed asynchronously:
var responseAsync = client
.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
// responseAsync.join(); // Wait for completion
An example POST request:
var request = HttpRequest
.newBuilder()
.uri(uri)
.version(HttpClient.Version.HTTP_2)
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer fake")
.POST(BodyPublishers.ofString("{ title: 'This is cool' }"))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
For sending form data as multipart (multipart/form-data
) or url-encoded (application/x-www-form-urlencoded
) format, see this solution.
See this article for examples and more information about HTTP Client API.
For Java standard library HTTP server, see this post.

- 18,032
- 13
- 118
- 133