Pages

http get request in java

http get request in java

  • In java there are many libraries to verify http get method.one of the library easy to use httpClient.
  • An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder. The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc. Once built, an HttpClient is immutable, and can be used to send multiple requests.
  • In order to use httpClient download httpClient jar from mvn repository or add dependency in your project.
Key notes about GET method:
  • GET method is used to retrieve information from server using URI.
  • GET request can be cached, bookmarked and remained in browser history.
  • GET requests have length restrictions.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.HttpClientBuilder;
import java.util.Scanner;

public class getDemo {
public static void main(String[] args) throws Exception {
HttpClient httpclient = HttpClientBuilder.create().build();

HttpGet httpget = new HttpGet("https://reqres.in/api/users?page=2");

System.out.println("Request Type: " + httpget.getMethod());

httpget.addHeader("Content-Type", "application/json");

// Executing the Get request
HttpResponse httpresponse = httpclient.execute(httpget);

Scanner sc = new Scanner(httpresponse.getEntity().getContent());

// Printing the status line
System.out.println(httpresponse.getStatusLine());
while (sc.hasNext()) {
System.out.println(sc.nextLine());
}

}
}
Output:
http get request in java
http get request in java
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.