Thursday, March 20, 2014

HTTP GET/POST Example

Following example can be used to send HTTP GET or POST request to web server using JAVA application.

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

String url = "http://seguide.blogspot.com";

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

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 = "http://seguide.blogspot.com";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

post.setHeader("User-Agent", USER_AGENT);

List urlParameters = new ArrayList();
urlParameters.add(new BasicNameValuePair("name", "sujith"));
urlParameters.add(new BasicNameValuePair("pass", "abc123"));
urlParameters.add(new BasicNameValuePair("param1", "param1"));
urlParameters.add(new BasicNameValuePair("param2", "param2"));

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