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());
 }
}
Read More

Sending Email using Java

To send an email using Java Application, you need JavaMail API and Java Activation Framework (JAF). You can download the latest version of JavaMail API from Java's website. Click here to open the Java's website. For the download of latest version of JAF you can click here.

Just download and extract those files in your machine. You will find number of files but you only need mail.jar and activation.jar. Just add those files in your project CLASSPATH.

Send a Simple E-mail

Before sending a simple email, first you have to connect your machine with the internet. Here is a sample code for sending a simple email. Create a project in any IDE (I am using Eclipse) and create a java file named as SendEmail.java and paste the below code.

// File Name SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {
   public static void main(String [] args) { 
      // Recipient's email ID needs to be mentioned.
      String to = "abc@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "xyz@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new
         InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");

      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Now just run this file as Java Application and your email will be sent to the recipient's email address.

If you have multiple recipient for sending the email, then you can specify the multiple email id as follows:

void addRecipients(Message.RecipientType type, Address[] addresses)throws MessagingException

Here, type can be set to TO, CC or BCC. CC represents Carbon Copy and BCC represents Black Carbon Copy. Example, Message.RecipientType.TO and addresses is the array of email ID. You have to use InternetAddress() method for specifying email IDs.

User Authentication

If sending email fails due to required authentication to the mail server then you can provide the user authentication by following ways and the rest of the process is as it is.


properties.setProperty("mail.user", "myuser");
properties.setProperty("mail.password", "mypwd");
Read More

Difference between AWT and Swing?

AWT is a Java interface to native system GUI code present in your OS. It will not work the same on every system, although it tries.

Swing is a more-or-less pure-Java GUI. It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, check-boxes, etc., into that window and responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of letting the operating system handle it. Thus Swing is 100% portable and is the same across platforms (although it is skinnable and has a "plug-gable look and feel" that can make it look more or less like how the native windows and widgets would look).

These are vastly different approaches to GUI toolkits and have a lot of consequences. A full answer to your question would try to explore all of those. :) Here are a couple:

AWT is a cross-platform interface, so even though it uses the underlying OS or native GUI toolkit for its functionality, it doesn't provide access to everything that those tool kits can do. Advanced or newer AWT widgets that might exist on one platform might not be supported on another. Features of widgets that aren't the same on every platform might not be supported, or worse, they might work differently on each platform. People used to invest lots of effort to get their AWT applications to work consistently across platforms - for instance, they may try to make calls into native code from Java.

Because AWT uses native GUI widgets, your OS knows about them and handles putting them in front of each other, etc., whereas Swing widgets are meaningless pixels within a window from your OS's point of view. Swing itself handles your widgets' layout and stacking. Mixing AWT and Swing is highly unsupported and can lead to ridiculous results, such as native buttons that obscure everything else in the dialog box in which they reside because everything else was created with Swing.

Because Swing tries to do everything possible in Java other than the very raw graphics routines provided by a native GUI window, it used to incur quite a performance penalty compared to AWT. This made Swing unfortunately slow to catch on. However, this has shrunk dramatically over the last several years due to more optimized JVMs, faster machines, and (I presume) optimization of the Swing internals. Today a Swing application can run fast enough to be serviceable or even zippy, and almost indistinguishable from an application using native widgets. Some will say it took far too long to get to this point, but most will say that it is well worth it.

Finally, you might also want to check out SWT (the GUI toolkit used for Eclipse, and an alternative to both AWT and Swing), which is somewhat of a return to the AWT idea of accessing native Widgets through Java.
Read More

Jetty Application Server

How to Install Jetty Application Server
Jetty is an open-source Servlet container and Application Server which is known to be lightweight, portable, robust, flexible, extensible and providing support for various technologies like SPDY, WebSocket, OSGi, JMX, JNDI, and JAAS. Jetty is very convenient for development and also widely used in production environments.

Jetty presents Standalone, Embedded and Jetty Maven Plugin modes of operation.

- Download Jetty binaries from the Jetty Homepage
- First we have to extract the zip (or tgz) archive to a convenient directory. After extracting the binaries, have to go inside the root directory of the extracted folder and execute the following command.
java -jar start.jar
- If we see similar output like this 2015-11-06 23:00:18.042:INFO:oejs.Server:main: Started @1021ms at the end of the terminal then the Jetty is successfully started.
- To verify it through the browser, have to navigate to this url http://localhost:8080/ and we will get Error 404 - Not Found page with Jetty Server signature at the end like Powered by Jetty:// 9.3.5.v20151012

Running Web Applications In Jetty
Create a WAR file and drop that file in the webapps folder. We do not even need to restart Jetty. webapps directory is monitored periodically and new applications are deployed automatically.

Changing the Jetty Port
By default, Jetty runs on 8080. In order to change it to some other port, we have to do the following:
- Open start.ini under Jetty root directory.
- Add this line jetty.port=7070
- Save and close the file.
Read More

WildFly Server

WildFly is an application server which is flexible and lightweight that helps us build amazing application. It is authorized by JBoss and now developed by Red Hat. This application server is written in Java and implements the Java Platform, Enterprise Edition (Java EE) specification and runs on multiple platforms.

Some features of WildFly Server
1. Unparalleled Speed
     - Fast Startup
     - Ultimate Web Performance & Scalability
2. Exceptionally Lightweight
     - Memory Diet
     - Slimable / Customizable Runtime
3. Powerful Administration
     - Unified configuration & Management
     - Domain & Standalone Management
4. Supports Latest Standards and Technology
     - Java EE 7
     - Modern Web
5. Modular Java
     - No more jar
     - Fast Linking & Concurrent Loading
6. Easily Testable
     - Arquillian

     - Smarter Development
Read More

Ten Reasons to Teach Coding.

What is coding? Why to code? How to code? Which language is easy to code? Which language is best to code? These are some questions that will come at least once across the student's mind. In simple way, we can say that coding is simply writing code in any programming language to solve some problem. Without any problem, there is no meaning of writing code. Actually, in the coding universe, there is always at least a problem to solve that the programmer solve using his/her logic in programming language. Coding is syntax specific. That is, every programming language has it's own syntax that we should follow while writing code. Also, we should choose language to code according to the nature of problem.

Here, in this post, I am going to present some ten reasons to teach coding to students.
1. Coding allows students to create content, not just consume it.
2. Coding empowers students and gives them tools to express themselves in really cool ways.
3. Coding teaches story telling with games and animations.
4. Coding is a place for students to take risks and fail safely.
5. Coding is inclusive and builds self-confidence.
6. Coding supports many principles of mathematics.
7. Coding teaches problem-solving and critical / analytical thinking skills.
8. Coding is a new type of literacy and will be a large part of future jobs.
9. Coding develops teamwork and collaborative skills.
10. Coding can help humanity by building human helping devices / machines.
Read More

Why is the keyboard layout QWERTY?

Why is the keyboard layout Q-W-E-R-T-Y and not simply A-B-C-D-F? Why were computer keyboards designed in the current format not in a alphabetical order. Is there any specific reason or it's just some random convention we are following?

It hasn’t been done randomly or just for fun, it has a very distinct and purposeful reason behind it.

The current format of the keyboard was devised long back in 1870’s by a gentleman named Christopher Sholes for the then typewriter.

Though, it definitely was not the first format to come up, it didn’t take much time to switch to this one.

Starting with lexicographic order i.e. A-B-C-D-E-F, after various trials and errors and taking hundreds of cases, Christopher Sholes gradually reached the Q-W-E-R-T-Y. It was really well received (evident from the fact that we still use it).

When the typewriter was invented, it used a metal bar to hold the character alphabets and the other end of the bar was attached to a linkage carrying a carriage with the coated ink.

When a key was struck, it would emboss its character on the paper placed beneath the carriage. However, when an operator learned to type at a great speed, a certain flaw was noticed.

When two letters were struck in quick succession, the bars of the typewriter would entangle and get jammed.

Christopher Sholes found a way out. He proposed that the letters of frequently used letter pairs should be in different rows.

 For example, ‘C-H’, ‘S-T’, ’T-H’, ‘W-H’ and more.

He also formulated that to speed up the typing process, there has to be a regular alternation between two hands. So observing thousands of words, he placed the letters in way that most words would make use of both hands.

He also observed that almost every word in the dictionary carries a vowel.

According to him, the most frequently used vowel was ‘A’ and the most frequently used letter (non-vowel) was ‘S’. So he placed ‘A’ and ‘S’ together and chose to keep less common letters like ‘Q’, ‘W’, ‘Z’, ‘X’, ‘C’ around these.

This was complemented by placing fairly common letters like ‘M’, ‘N’, ‘L’, ‘K’, ‘O’, ‘P’ at right extremes to create a perfect alternation between both the hands.

All these factors tested with thousands of trials gave us the format that we still use and perhaps would be using till eternity.
Read More