Java Send Http Response Example
HttpURLConnection class from java.net
package can be used to send Java HTTP Request programmatically. Today we will learn how to use HttpURLConnection
in java program to send GET and POST requests and then print the response.
Java HTTP Request
For our HttpURLConnection example, I am using sample project from Spring MVC Tutorial because it has URLs for GET and POST HTTP methods. Below are the images for this web application, I have deployed it on my localhost tomcat server.
Java HTTP GET Request
Java HTTP GET Request for Login Page
Java HTTP POST Request
For Java HTTP GET requests, we have all the information in the browser URL itself. So from the above images, we know that we have the following GET request URLs.
- https://localhost:9090/SpringMVCExample/
- https://localhost:9090/SpringMVCExample/login
Above URL's don't have any parameters but as we know that in HTTP GET requests parameters are part of URL itself, so for example if we have to send a parameter named userName with value as Pankaj then the URLs would have been like below.
- https://localhost:9090/SpringMVCExample?userName=Pankaj
- https://localhost:9090/SpringMVCExample/login?userName=Pankaj&pwd=apple123 – for multiple params
If we know the POST URL and what parameters it's expecting, it's awesome but in this case, we will figure it out from the login form source.
Below is the HTML code we get when we view the source of the login page in any of the browsers.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Page</title> </head> <body> <form action="home" method="post"> <input type="text" name="userName"><br> <input type="submit" value="Login"> </form> </body> </html>
Look at the form method in the source, as expected it's POST method. Now see that action is "home", so the POST URL would be https://localhost:9090/SpringMVCExample/home. Now check the different elements in the form, from the above form we can deduce that we need to send one POST parameter with name userName and it's of type String.
So now we have complete details of the GET and POST requests and we can proceed for the Java HTTP Request example program.
Below are the steps we need to follow for sending Java HTTP requests using HttpURLConnection
class.
- Create
URL
object from the GET/POST URL String. - Call openConnection() method on URL object that returns instance of
HttpURLConnection
- Set the request method in
HttpURLConnection
instance, default value is GET. - Call setRequestProperty() method on
HttpURLConnection
instance to set request header values, such as "User-Agent" and "Accept-Language" etc. - We can call
getResponseCode()
to get the response HTTP code. This way we know if the request was processed successfully or there was any HTTP error message thrown. - For GET, we can simply use Reader and InputStream to read the response and process it accordingly.
- For POST, before we read response we need to get the OutputStream from
HttpURLConnection
instance and write POST parameters into it.
HttpURLConnection Example
Based on the above steps, below is the example program showing usage of HttpURLConnection
to send Java GET and POST requests.
HttpURLConnectionExample.java code:
package com.journaldev.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { private static final String USER_AGENT = "Mozilla/5.0"; private static final String GET_URL = "https://localhost:9090/SpringMVCExample"; private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home"; private static final String POST_PARAMS = "userName=Pankaj"; public static void main(String[] args) throws IOException { sendGET(); System.out.println("GET DONE"); sendPOST(); System.out.println("POST DONE"); } private static void sendGET() throws IOException { URL obj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result System.out.println(response.toString()); } else { System.out.println("GET request not worked"); } } private static void sendPOST() throws IOException { URL obj = new URL(POST_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); // For POST only - START con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(POST_PARAMS.getBytes()); os.flush(); os.close(); // For POST only - END int responseCode = con.getResponseCode(); System.out.println("POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { //success BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result System.out.println(response.toString()); } else { System.out.println("POST request not worked"); } } }
When we execute the above program, we get below response.
GET Response Code :: 200 <html><head> <title>Home</title></head><body><h1> Hello world! </h1><P> The time on the server is March 6, 2015 9:31:04 PM IST. </P></body></html> GET DONE POST Response Code :: 200 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj</h3></body></html> POST DONE
Just compare it with the browser HTTP response and you will see that it's same. You can also save response into any HTML file and open it to compare the responses visually.
Quick Tip: If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection
instead of java.net.HttpURLConnection
. Rest all the steps will be same as above, HttpsURLConnection
will take care of SSL handshake and encryption.
Source: https://www.journaldev.com/7148/java-httpurlconnection-example-java-http-request-get-post
0 Response to "Java Send Http Response Example"
Enregistrer un commentaire