Send HTTP request GET/POST in Java - TechDoko

Hot

Post Top Ad

Send HTTP request GET/POST in Java

HTTP stands for Hypertext Transfer Protocol. It is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a web site may be the server. A web browser sends HTTP request to an application that resides on the remote host computer and the application responses to that request. HTTP request can be of different type.

In this post I am going to give an example of HTTP GET/POST request using Java.

1. Java HttpURLConnection example

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

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("Testing 1 - Send Http GET request");
  http.sendGet();
  System.out.println("\nTesting 2 - Send Http POST request");
  http.sendPost();
 }

  // HTTP GET request
  private void sendGet() throws Exception {
  String url = "http://www.google.com/search?q=nepal";
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();

  // optional default is GET
  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());
 }


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

 }
}

2. Apache HttpClient

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientExample {
 private final String USER_AGENT = "Mozilla/5.0";

 public static void main(String[] args) throws Exception {
  HttpClientExample http = new HttpClientExample();
  System.out.println("Testing 1 - Send Http GET request");
  http.sendGet();
  System.out.println("\nTesting 2 - Send Http POST request");
  http.sendPost();
 }

 // HTTP GET request
 private void sendGet() throws Exception {
  String url = "http://www.google.com/search?q=developer";

  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet(url);

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

  HttpResponse response = client.execute(request);
  System.out.println("\nSending 'GET' request to URL :" + url);
  System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

  BufferedReader rd = new BufferedReader(new
InputStreamReader( response.getEntity().getContent()));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
   result.append(line);
  }
  System.out.println(result.toString());
 }

 // HTTP POST request
 private void sendPost() throws Exception {
  String url ="https://selfsolve.apple.com/wcResults.do";
  HttpClient client = new DefaultHttpClient();
  HttpPost post = new HttpPost(url);

  // add header
  post.setHeader("User-Agent", USER_AGENT);
  List urlParameters = new ArrayList();
  urlParameters.add(new BasicNameValuePair("sn","C02G8416DRJM"));
  urlParameters.add(new BasicNameValuePair("cn", ""));
  urlParameters.add(new BasicNameValuePair("locale",""));
  urlParameters.add(new BasicNameValuePair("caller",""));
  urlParameters.add(new BasicNameValuePair("num","12345"));

  post.setEntity(new UrlEncodedFormEntity(urlParameters));

  HttpResponse response = client.execute(post);
  System.out.println("\nSending 'POST' request to URL: " + url);
  System.out.println("Post parameters : " +post.getEntity());
  System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

  BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
   result.append(line);
  }
  System.out.println(result.toString());
 }
}

No comments:

Post a Comment