Sunday, January 8, 2017

Java How to send HTTP GET/POST

In this post, I will show you standard method to make HTTP GET/POST request using java.





I. HttpURLConnection
1. Send an HTTP GET request to https://www.amazon.com/


public class HttpURLConnectionExample {

 private final String USER_AGENT = "Mozilla/5.0";

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

  HttpURLConnectionExample http = new HttpURLConnectionExample();

  System.out.println("Send Http GET request");
  http.sendGet();

 }

 // HTTP GET request
 private void sendGet() throws Exception {

  String url = "http://www.amazon.com/";

  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();

  con.setRequestMethod("GET");

  //add request header
  con.setRequestProperty("User-Agent", USER_AGENT);

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'GET' request to URL : " + url);
  System.out.println("Response Code : " + responseCode);

  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());

 }

2. Send an HTTP POST request to apple.com


public class HttpURLConnectionExample {

 private final String USER_AGENT = "Mozilla/5.0";

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

  HttpURLConnectionExample http = new HttpURLConnectionExample();
  System.out.println("Send Http POST request");
  http.sendPost();

 }

 // HTTP POST request
 private void sendPost() throws Exception {

  String url = "https://selfsolve.apple.com/wcResults.do";
  URL obj = new URL(url);
  HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

  //add request header
  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

  String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

  // Send post request
  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(urlParameters);
  wr.flush();
  wr.close();

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post parameters : " + urlParameters);
  System.out.println("Response Code : " + responseCode);

  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());

 }

}
Good luck!
Share:

0 comments:

Post a Comment

Total Pageviews