How to send HTTPRequest GET/POST Using Java or HttpClient
In this article I will show you with example of GET/POST
Request via standard Java and apache client library.
I.e. HttpURLConnection
and HttpClient library.
1 : Java
HttpURLConnection
for example
package test.http;
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 HttpURLConnectionTest {
/**
* @param args
*/
public static void main(String[] args) {
HttpURLConnectionTest http=new HttpURLConnectionTest();
//http.sendGETRequest();
http.sendPOSTRequest();
}
private void sendGETRequest(){
String url = "http://www.google.com";
try{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("Sending 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();
System.out.println(response.toString());
}catch(Exception ex){
ex.printStackTrace();
}
}
private void sendPOSTRequest(){
String url = "http://www.mginger.com/login.jsp";
try{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) 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 = "j_username=wakil&j_password=ahamad123343";
// 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("Sending 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());
}catch(Exception ex){
ex.printStackTrace();
}
}
}
When you run the following output comes here :
Sending GET request to URL : http://www.google.com
Response Code : 200
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><title>Google</title><script>(function(){window.google={kEI:"CpupUZyyA4SIrAf164GQDA",getEI:function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI},https:function()
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
Sending POST request to URL : http://www.mginger.com/login.jsp
Post parameters : j_username=wakil&j_password=ahamad123343
Response Code : 200
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Get Deals | Earn Rewards | Free SMS | Games | Coupons - mGinger.com</title> <style type="text/css"> @import "/mobile/css/style.css"; </style>
--------------------------------------------------
--------------------------------------------------
</html>
--------------------------------------------------
--------------------------------------------------
</html>
2 : HttpClient
for example
package test.http;
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 HttpClientTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HttpClientTest http=new HttpClientTest();
http.sendGETRequest();
http.sendPOSTRequest();
}
// HTTP GET request
private void sendGETRequest() 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("Sending 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 sendPOSTRequest() throws Exception {
String url = "http://www.mginger.com/login";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("j_username", "wakil"));
urlParameters.add(new BasicNameValuePair("j_password", "qwqweqe"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Sending 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());
}
}
