Categories
Android Java

Android HttpRequest class (version 2.1)

Version of of this class had some bugs so I corrected them and here is the latest version 🙂

Enjoy!

package moz.http;

import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.http.client.HttpClient;
import org.apache.commons.*;
import android.util.Log;
/**
* HTTP Request class
*
* You can use this class and distribute it as long as you give proper credit
* and place and leave this notice intact :). Check my blog for updated
* version(s) of this class (http://moazzam-khan.com)
*
* Usage Examples:
*
* Get Request
* --------------------------------
* HttpData data = HttpRequest.get("http://example.com/index.php?user=hello");
* System.out.println(data.content);
*
* Post Request
* --------------------------------
* HttpData data = HttpRequest.post("http://xyz.com", "var1=val&var2=val2");
* System.out.println(data.content);
* Enumeration keys = dat.cookies.keys(); // cookies
* while (keys.hasMoreElements()) {
* 		System.out.println(keys.nextElement() + " = " +
* 				data.cookies.get(keys.nextElement() + "rn");
*	}
* Enumeration keys = dat.headers.keys(); // headers
* while (keys.hasMoreElements()) {
* 		System.out.println(keys.nextElement() + " = " +
* 				data.headers.get(keys.nextElement() + "rn");
*	}
*
* Upload a file
* --------------------------------
* ArrayList files = new ArrayList();
* files.add(new File("/etc/someFile"));
* files.add(new File("/home/user/anotherFile"));
*
* Hashtable ht = new Hashtable();
* ht.put("var1", "val1");
*
* HttpData data = HttpRequest.post("http://xyz.com", ht, files);
* System.out.println(data.content);
*
* @author Moazzam Khan
*/
public class HttpRequest {

        /**
        * HttpGet request
        *
        * @param sUrl
        * @return
        */
        public static HttpData get(String sUrl) {
                HttpData ret = new HttpData();
                String str;
                StringBuffer buff = new StringBuffer();
                try {
                        URL url = new URL(sUrl);
                        URLConnection con = url.openConnection();

                        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        while ((str = in.readLine()) != null) {
                                buff.append(str);
                        }
                        ret.content = buff.toString();
                        //get headers
                        Map> headers = con.getHeaderFields();
                        Set>> hKeys = headers.entrySet();
                        for (Iterator>> i = hKeys.iterator(); i.hasNext();) {
                                Entry> m = i.next();

                                Log.w("HEADER_KEY", m.getKey() + "");
                                ret.headers.put(m.getKey(), m.getValue().toString());
                                if (m.getKey().equals("set-cookie"))
                                ret.cookies.put(m.getKey(), m.getValue().toString());
                        }
                } catch (Exception e) {
                        Log.e("HttpRequest", e.toString());
                }
                return ret;
        }




        /**
        * HTTP post request
        *
        * @param sUrl
        * @param ht
        * @return
        * @throws Exception
        */
        public static HttpData post(String sUrl, Hashtable ht) throws Exception {
                String key;
                StringBuffer data = new StringBuffer();
                Enumeration keys = ht.keys();
                while (keys.hasMoreElements()) {
                        key = keys.nextElement();
                        data.append(URLEncoder.encode(key, "UTF-8"));
                        data.append("=");
                        data.append(URLEncoder.encode(ht.get(key), "UTF-8"));
                        data.append("&");
                }
                return HttpRequest.post(sUrl, data.toString());
        }
        /**
        * HTTP post request
        *
        * @param sUrl
        * @param data
        * @return
        */
        public static HttpData post(String sUrl, String data) {
                StringBuffer ret = new StringBuffer();
                HttpData dat = new HttpData();
                String header;
                try {
                        // Send data
                        URL url = new URL(sUrl);
                        URLConnection conn = url.openConnection();
                        conn.setDoOutput(true);
                        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                        wr.write(data);
                        wr.flush();

                        // Get the response

                        Map> headers = conn.getHeaderFields();
                        Set>> hKeys = headers.entrySet();
                        for (Iterator>> i = hKeys.iterator(); i.hasNext();) {
                                Entry> m = i.next();

                                Log.w("HEADER_KEY", m.getKey() + "");
                                dat.headers.put(m.getKey(), m.getValue().toString());
                                if (m.getKey().equals("set-cookie"))
                                dat.cookies.put(m.getKey(), m.getValue().toString());
                        }
                        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String line;
                        while ((line = rd.readLine()) != null) {
                                ret.append(line);
                        }

                        wr.close();
                        rd.close();
                } catch (Exception e) {
                        Log.e("ERROR", "ERROR IN CODE:"+e.getMessage());
                }
                dat.content = ret.toString();
                return dat;
        }
        /**
        * Post request (upload files)
        * @param sUrl
        * @param files
        * @return HttpData
        */
        public static HttpData post(String sUrl, ArrayList files)
        {
                Hashtable ht = new Hashtable();
                return HttpRequest.post(sUrl, ht, files);
        }
        /**
        * Post request (upload files)
        * @param sUrl
        * @param params Form data
        * @param files
        * @return
        */
        public static HttpData post(String sUrl, Hashtable params, ArrayList files) {
                HttpData ret = new HttpData();
                try {
                        String boundary = "*****************************************";
                        String newLine = "rn";
                        int bytesAvailable;
                        int bufferSize;
                        int maxBufferSize = 4096;
                        int bytesRead;

                        URL url = new URL(sUrl);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setDoInput(true);
                        con.setDoOutput(true);
                        con.setUseCaches(false);
                        con.setRequestMethod("POST");
                        con.setRequestProperty("Connection", "Keep-Alive");
                        con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                        DataOutputStream dos = new DataOutputStream(con.getOutputStream());

                        //dos.writeChars(params);

                        //upload files
                        for (int i=0; i 0) {
                                        dos.write(buffer, 0, bufferSize);
                                        bytesAvailable = fis.available();
                                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                        bytesRead = fis.read(buffer, 0, bufferSize);
                                }
                                dos.writeBytes(newLine);
                                dos.writeBytes("--" + boundary + "--" + newLine);
                                fis.close();
                        }
                        // Now write the data

                        Enumeration keys = params.keys();
                        String key, val;
                        while (keys.hasMoreElements()) {
                                key = keys.nextElement().toString();
                                val = params.get(key);
                                dos.writeBytes("--" + boundary + newLine);
                                dos.writeBytes("Content-Disposition: form-data;name=""
                                + key+""" + newLine + newLine + val);
                                dos.writeBytes(newLine);
                                dos.writeBytes("--" + boundary + "--" + newLine);

                        }
                        dos.flush();

                        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                        String line;
                        while ((line = rd.readLine()) != null) {
                                ret.content += line + "rn";
                        }
                        //get headers
                        Map> headers = con.getHeaderFields();
                        Set>> hKeys = headers.entrySet();
                        for (Iterator>> i = hKeys.iterator(); i.hasNext();) {
                                Entry> m = i.next();

                                Log.w("HEADER_KEY", m.getKey() + "");
                                ret.headers.put(m.getKey(), m.getValue().toString());
                                if (m.getKey().equals("set-cookie"))
                                ret.cookies.put(m.getKey(), m.getValue().toString());
                        }
                        dos.close();
                        rd.close();
                } catch (MalformedURLException me) {

                } catch (IOException ie) {

                } catch (Exception e) {
                        Log.e("HREQ", "Exception: "+e.toString());
                }
                return ret;
        }
}

You will also need the class below:

package moz.http;
import java.util.Hashtable;
public class HttpData {
      public String content;
      public Hashtable cookies = new Hashtable();
      public Hashtable headers = new Hashtable();
}
Categories
Java Uncategorized

Java 101 – Lesson 4 – Variables

We know how to compile and run a basic Java application. We also know the basic structure of code for Java. If you don’t know what I am talking about, please refer to the previous articles in the Java 101 series (lessons 1, 2 and 3). In this article, we will take a look at variables and how to use them.

What is a variable? A variable is a container which holds information. Containers come in all shapes and sizes. We know that they have a limitation to what they can hold (or what can be stored inside them). You can’t put a shoe in a container that is meant for storing pens (it would be too small). Variables have these limitations too.

Types of variables :

  • int (stores integers. Ex: -1, -2, 9, 4)
  • float (stores floating point numbers. Ex: 2.3, 2.0, -9.75)
  • double (stores floating point numbers also but has a larger size)
  • String (stores text. Ex: “Hello world”, “Java 101”)
  • boolean (stores true or false)

A variable will only hold a value (information) that is of its type. An int will only hold an integer. You can’t put a string in it.

You have to make a chair before you can sit on it. Makes sense right? How can you sit on a chair that doesn’t exist. Same is the case with variables. You have to declare them before you can store something in them.  Variables are declared like this :

int a;
int someNumber;
String greeting = “Good morning”;

You write the variable type first then write the variable name. In the above examples, variable types are written in purple and variable names are in black. A variable’s name is what you will use to refer to it (when you want to put something in it, see what’s in it, or take something out of it). There are some rules to how you can name a variable. They are (quoting from java.sun.com):

  • Variable names are case-sensitive. A variable’s name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign “$“, or the underscore character “_“. The convention, however, is to always begin your variable names with a letter, not “$” or “_“. Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it’s technically legal to begin your variable’s name with “_“, this practice is discouraged. White space is not permitted.
  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.
  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

You will notice that there is a ; (semi-colon) at the end of every line in the above example. It is required in Java. You have to place a semi-colon at the end of every statement. It’s presence tells Java where a statement ends (yes, you can have a statement on 2 lines but there has to be a semi-colon on the second line).

After you declare a variable, you can store values (numbers, text, etc) in it. This process is called assigning a value to a variable. You can assign a value to a variable when you declare, or after you declare it. It is done like this :

int numberOfCars; // Declare numberOfCars as an int
numberOfCars = 5; // assign the value 5 to numberOfCars
double weight = 152.50; // Declare weight as a double and assign 152.50 to it.

Now that we have an idea of what a variable is, let’s write a program that will utilize them.

import java.io.*;

public class VariableTest {
    public static void main(String[] args) {
        /* Declare variables */
        double numberOne = 14.0;
        double numberTwo = 13.5;
        double addResult;
        double diffResults;
        double prodResult;
        double diviResult;
         /* Add numberOne and numberTwo and put the sum in addResult */
         addResult = numberOne + numberTwo ;
         /* Subtract numberOne and numberTwo and put the difference in subResult */
         diffResult = numberOne - numberTwo;
         /* Multiply numberOne and numberTwo and put the product in prodResult */
         prodResult = numberOne * numberTwo;
         /* Divide numberOne and numberTwo and put the quotient in diviResult */
         diviResult = numberOne / numberTwo;

         /* Print out all the results */
         System.out.println("numberOne = "+numberOne);
         System.out.println("numberTwo = "+numberTwo);
         System.out.println("Their sum is : "+addResult);
         System.out.println("Their difference is : "+diffResult);
         System.out.println("Their product is : "+prodResult);
         System.out.println("Their quotient is : "+diviResult);
    }
}
Categories
Java Uncategorized

Java 101 – Lesson 3 – Dissecting Hello World

This article is a continuation of articles in the series of Java 101. You will need to read lesson 1 and lesson 2 to completely understand this article (or blog post, or whatever you want to call it).  In lesson 2, we executed a piece of code, which printed “Hello World” on the command prompt (also called the console). The code looked something like this :

/**
 * This is a package. You need to import this to print anything to the command prompt,
 * get information from the user on the command prompt, to read/write to a file, etc.
 * For now, just keep in mind that you need to have this line in almost all java applications
 * you write
 */
import java.io.*;

/**
 * This is a class which will contain the method you will run, to run your program.
 * As we move along in these tutorials, you will see that this is a common structure
 * in all Java applications. Everything is placed in a class. I will explain this more
 * when we learn about classes.
 *
 * Also this is a public class, which means it has to be put in a file whose name is
 * the same as its name (which will be HelloWorld.java). If you name this class
 * HelloJoe, then you will have to save this whole code in HelloJoe.java
 */
public class HelloWorld {
    /**
     * Forgive the cliche but this is a method which you will use in all Java applications
     * you will write. This method is run is the one that the Java Virtual Machine will
     * look for, when it is asked to run your application. Think of this as a starting point.
     */
    public static void main(String[] args) {
        /**
         * This is the place where you write your code. Give Java instructions on what you
         * want it to do, etc. In this case, we are just printing out a statement - "Hello World".
         * Just for fun, try changing the text "Hello World" to "I have ice cream" and run the
         * application. The statement "I have ice cream" will be printed on the command prompt
         */

        System.out.println("Hello world");
    }
}

I added some extra text in there to  make it easy to understand what each line is doing. Notice that the extra text I added is in between /* and */ . Any text placed in between /* and */ is called a comment. Comments are pieces of information that are ignored by the compiler when it compiles and runs your code. They are meant to explain what your code is supposed to do, which is very helpful when the code is 3000 lines. As we move through the lessons, I will place comments in my example code so you should have an idea of how they are generally used.

The comments in the above code should explain pretty much everything about the Hello World application (or program). What you can do is copy this same structure for any program you write. And, just to be clear this is the structure :

import java.io.*;

public class AnyClassName {
    public static void main(String[] args) {
         // This is where you will write your code. Everything else will remain the same
         // You can change the class name though (which is AnyClassName here)
    }
}

Now that we know the basic structure of a Java program we will start learning some actual programming in the next lesson.

Categories
Java Uncategorized

Java 101 – Lesson 2 – Getting familiar with Java

I’ve never been too fond of books when trying to learn a language for the first time. The reason is that they give you too many details in the beginning that you may not necessarily be interested in until later on. The approach that I’ve found to be very useful in learning or teaching is to let the user/student get an overview first and then go into how things actually work. So, in this article we are going to write a simple application/program and run it. As we move on, I will explain what is going on.

Hello World

For those who don’t know, Hello world is a very popular program in the computing world. Almost every language’s tutorial has one for beginners. All it does is print Hello world on the screen in one form or another. This is what we will do too. We will write a program that will print “Hello world” in your console window.

Create a folder in your c:\ drive and name it java_projects. This is where we will place all Java files.

Open notepad and type this in it :

import java.io.*;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}

After copying and pasting the above code in your notepad window, save the file as HelloWorld.java in c:\java_projects\ . When you save it, make sure that file type is selected to “All files” or notepad will save your file as “HelloWorld.java.txt” and not “HelloWorld.java” .

Saving Java file
Saving Java file

Oh, and you will have to save the file as HelloWorld.java (with the capital letters) or the code won’t compile. I will get to the reason in later articles.

We have written the code. Now, we need to compile and run it. We will do that by opening the command prompt (also referred to as the console) and do it from there. Click on start then on Run and type cmd in the dialog box that opens up.

Run dialog
Run dialog

A black window will appear with a blinking cursor. It is the command prompt. Type this in it :

cd c:\java_projects\

Then type :

javac HelloWorld.java

The screen will get stuck for a few seconds and then you will see a blinking cursor again. javac is used to compile java code into byte-code. If you go to c:\java_projects\ in windows explorer, you will see that there javac created a file called HelloWorld.class . This is the byte-code file that the command “java” needs to run the application. You can run your code by typing :

java HelloWorld

A line of text saying Hello world should appear in your console. Congratulations ! you just ran your first application.

Click to enlarge
Click to enlarge
Categories
Java Uncategorized

Java 101 – Lesson 1 – Installing the JDK

Since this is the first class, I guess I should talk about what Java is. Java is a language that can be used to write platform-independent desktop applications or web applications. The term “Platform independent” means that you can write the code for an application on Windows and run it in Linux or a Mac (as long as you have a JVM installed). In fact, you can run your program on any device – not just computers – if that device has a JVM available for it.

The story of how Java came into existence is very interesting. The first release of Java was in 1995. In the last 14 years, Java has come a long way from being something that just integrated into Netscape to being one of the most widely used languages in the computer industry.  I don’t want to bore everyone with the details of the history of Java’s birth so those who are interested can go to : http://java.sun.com/features/1998/05/birthday.html

How does Java work, you ask? When you write code in Java, you need to compile it using the javac command. When you compile your code, it is converted to “byte-code”. This byte-code is later read by JVM when you run your application using the java command. So, it’s a 2 step process.

To be able to make program in Java, you need to install the JDK (Java Development Kit). JDK comes with quite a few things but the ones we are interested in are the compiler, and the JVM. You may also have heard the term JRE (if you’ve ever had to install the JRE plugin for Internet Explorer). JRE stands for Java Runtime Environment. You can run Java applications with it but you can’t compile them.

Let’s get started with the installation then. Download the latest version of JDK from : http://java.sun.com/javase/downloads/index.jsp . The latest version of JDK is JDK 6 update 12 as of this writing. Here’s a link to download JDK6 update12 https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/[email protected]_Developer. Select your platform, etc and depending on your the speed of your internet connection, it should be done fairly quickly.

Double click the file you just downloaded and it will start the installation process. Follow the instructions that come up and after it’s done you should be ready to write code Java code – assuming nothing went wrong.

J2SE download
J2SE download

For Windows :

You have java installed, but now you need to add it to your path. Path is an environment variable in windows. All the folders in this variable are searched for, when you try to run a program without providing its location.

Click start then right click on “My Computer”. Select “Properties” from the menu that pops up. Go to the “Advanced” tab and press the “Environment variables” button in it.

Getting to system properties
Click to enlarge
Environment Variables
Click to enlarge

In the dialog that opens up, you will find a variable called path. Click on it and click on the edit button. If you have installed the JDK in the default path, then your JDK will be installed in C:\Program Files\Java. You need to get the location for the bin folder in your JDK. For, JDK6 Update12 it is : C:\Program Files\Java\jdk1.6.0_12\bin . Go to the end in the “Variable value” textbox and type ; then type in the location to the bin folder for your JDK. In the end you will have written something like this :

;C:\Program Files\Java\jdk1.6.0_12\bin

Here’s a few pictures to make things easier 🙂

Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge

And, viola! You’re done.