📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
HTTP
The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.HTTP GET
The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data.HTTP POST
The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.Java HTTP GET Request with HttpURLConnection
package net.javaguides.network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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://www.google.com/search?q=javaguides";
public static void main(String[] args) throws IOException {
sendHttpGETRequest();
}
private static void sendHttpGETRequest() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpURLConnection.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.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");
}
for (int i = 1; i <= 8; i++) {
System.out.println(httpURLConnection.getHeaderFieldKey(i) + " = " + httpURLConnection.getHeaderField(i));
}
}
}
GET Response Code :: 200
Google search result ....
Date = Tue, 14 May 2019 08:50:16 GMT
Expires = -1
Cache-Control = private, max-age=0
Content-Type = text/html; charset=UTF-8
P3P = CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server = gws
X-XSS-Protection = 0
X-Frame-Options = SAMEORIGIN
Java HTTP POST Request with HttpURLConnection
package net.javaguides.network;
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 POST_URL = "http://localhost:8080/login-jsp-jdbc-mysql-example/login.jsp";
private static final String POST_PARAMS = "userName=Ramesh&password=Pass@123";
public static void main(String[] args) throws IOException {
sendPOST();
}
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = httpURLConnection.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.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");
}
}
}
Using the Apache HttpClient - Add Dependency
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
Java HTTP GET Request with Apache HTTPClient
package com.javadevelopersguide.httpclient.examples;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* This example demonstrates the use of {@link HttpGet} request method.
* @author Ramesh Fadatare
*/
public class HttpGetRequestMethodExample {
public static void main(String...args) throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
//HTTP GET method
HttpGet httpget = new HttpGet("http://httpbin.org/get");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler < String > responseHandler = response - > {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}
}
Executing request GET http://httpbin.org/get HTTP/1.1
----------------------------------------
{
"args": {},
"headers": {
"Accept-Encoding": "gzip,deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
},
"origin": "49.35.12.218",
"url": "http://httpbin.org/get"
}
Java HTTP POST Request with Apache HTTPClient
package com.javadevelopersguide.httpclient.examples;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* This example demonstrates the use of {@link HttpPost} request method.
* @author Ramesh Fadatare
*/
public class HttpPostRequestMethodExample {
public static void main(String[] args) throws IOException {
postUser();
}
public static void postUser() throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
String json = "{\r\n" +
" \"firstName\": \"Ram\",\r\n" +
" \"lastName\": \"Jadhav\",\r\n" +
" \"emailId\": \"ramesh1234@gmail.com\",\r\n" +
" \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
" \"createdBy\": \"Ramesh\",\r\n" +
" \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
" \"updatedby\": \"Ramesh\"\r\n" +
"}";
StringEntity stringEntity = new StringEntity(json);
httpPost.setEntity(stringEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
// Create a custom response handler
ResponseHandler < String > responseHandler = response - > {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}
}
Output
Executing request POST http://localhost:8080/api/v1/users HTTP/1.1
----------------------------------------
{"id":37,"firstName":"Ram","lastName":"Jadhav","emailId":"ramesh1234@gmail.com",
"createdAt":"2018-10-29T09:37:09.821+0000","createdBy":"Ramesh","updatedAt":"2018-10-29T09:37:09.821+0000",
"updatedby":"Ramesh"}
Comments
Post a Comment
Leave Comment