Sending HTTP GET Request to a REST API in JAVA

HTTP/HTTPS Get/Post request /response using JAVA below.

For detailed visit here:

https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnection {

 public static void main(String[] args) throws IOException {

  String response = httpGet("https://services.groupkt.com/state/get/IND/all");
 }

 public static String httpGet(String urlStr) throws IOException {

  URL obj = new URL(urlStr);
  HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
  System.out.println(con.getResponseCode());

  if (con.getResponseCode() != 200) {

   throw new IOException(con.getResponseMessage());

  }
  // buffer the result into string

  
  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();

  con.disconnect();
  return response.toString();

 }

}
Advertisements

One thought on “Sending HTTP GET Request to a REST API in JAVA

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s