SykoTheKiD
11/28/2015 - 3:21 AM

Send GET and POST Requests in Java

Send GET and POST Requests in Java

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

public class HTTPRequest {
	private String url;
	final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11";

	public HTTPRequest(String url) {
		this.url = url;
	}

	public HTTPResponse get() throws IOException {
		URL obj = new URL(this.url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod(HTTPMethods.GET);
		con.setRequestProperty("User-Agent", USER_AGENT);
		int responseCode = con.getResponseCode();
		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuilder response = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		return new HTTPResponse(responseCode, response.toString());
	}

	public HTTPResponse post(String postParams) throws IOException {
		URL obj = new URL(this.url);
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
		con.setRequestMethod(HTTPMethods.POST);
		con.setRequestProperty("User-Agent", USER_AGENT);
		String postData = postParams;
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(postData);
		wr.flush();
		wr.close();
		int responseCode = con.getResponseCode();
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuilder response = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		return new HTTPResponse(responseCode, response.toString());
	}

	public String getUrl() {
		return url;
	}
	
	/*
	* This class should be in a separate file
	*/
	
	public final class HTTPMethods{
	  public static final String GET = "GET";
	  public static final String POST = "POST";
	  public static final String PUT = "PUT";
	  public static final String DELETE = "DELETE";
	}
	
	/*
	* This class should be in a separate file
	*/
	public class HTTPResponse {
    		private int responseCode;
    		private String reponse;

    		public HTTPResponse(int responseCode, String response) {
        		this.responseCode = responseCode;
        		this.reponse = response;
    		}
    		public int getResponseCode() {
        		return responseCode;
    		}

    		public String getReponse() {
        		return reponse;
    		}
	}

}