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

Comments

42 responses to “Android HttpRequest class (version 2.1)”

  1. hakimapia Avatar
    hakimapia

    Hi I didn’t find any HttpData Class in the documentation. Do you have a separate class for that?

  2. Moazzam Avatar

    Sorry about that. I had put the HttpData class in the original version of the code. I added it here, too (in the post)

    Let me know in case you face any other problems with it.

  3. Craig Avatar
    Craig

    I’m trying to upload an image to a form using this script, and if I attach the image as a file and then try a POST the entire request is empty. Even if I have a Hashmap with a name value pair also attached, attaching an image blanks the whole request.

    Any idea why that might be?

  4. Craig Avatar
    Craig

    I got it working! Thanks! It was failing I think because I didn’t correctly resolve the issues with the missing backslashes initially.

    Thanks again for this code!

  5. Bram Avatar
    Bram

    Someone stole your code: sanderborgman.nl/android/android-httprequest-class/

    Anyway, thanks for the code ! Works like a charm.

  6. Tony Avatar
    Tony

    Ok, this is better than v2. Please put a note up on v2 to see v2.1. Thanks.

  7. Tony Avatar
    Tony

    Missing backslashes:

    String newLine = “rn”;
    ——————————

    should be

    String newLine = “\r\n”;

  8. Tony Avatar
    Tony

    Also, thanks ๐Ÿ™‚ Code works!

  9. Moazzam Avatar

    Thanks for pointing out the missing backslashes, Tony. I will correct them right now.

  10. kreia Avatar
    kreia

    When multiple form-variable and/or file data submitted, it will be failed due to wrong seperation of “Content-Disposition” block. For perfection, the part

    dos.writeBytes(“–” + boundary + “–” + newLine);

    line in form-data generation block, should be removed.
    BTW, your code is very helpful. Thanks!

  11. Roderick Avatar

    Hey great work!
    Just one thing: (in addition to the above mentioned \r\n problem): I found more missing backslashes:

    dos.writeBytes(“Content-Disposition: form-data; ”
    + “name=\”file_”+i+”\”;filename=\””

    dos.writeBytes(“Content-Disposition: form-data;name=\””
    + key+”\”” + newLine + newLine + val);

    I think it’s the page’s ‘code-viewer’ or our browsers that ignores them, so maybe a link a zipped package would work?

    Anyway, thanks to Eclipse I quickly found and corrected the errors, wasn’t that hard. The incorrect \r\n characters I *did* miss at first so thanks tony ๐Ÿ˜€

  12. David Avatar
    David

    HI Moazzam,

    Awesome work!

    Could please explain me file up loader. I’m not getting the code. How you have establish the url to take the file upload service. Do you have any public url by which i can test this code?

  13. Moazzam Avatar

    Hi David,

    You need two things to upload a file from Android to a web server.
    1 – A script on your server which can handle file uploads
    2 – This Android library in my blog post.

    Every language has its own way of handling file uploads so I would suggest googling for handle file uploads

    HTH

  14. Moazzam Avatar

    Thanks for letting me know Roderick. I will try to attach a zip file next time. I was hoping I wouldn’t have to do that, but oh well.

  15. David Avatar
    David

    Moazzam,

    Thanks for your reply! Do you have any public server available to test this code? I didn’t found any server otherwise i have to host the new server.

  16. Moazzam Avatar

    Hi David,

    Unfortunately, I don’t provide free webhosting. I do, however, provide, paid webhosting if you are interested. Let me know if you are interested and I will provide more details

  17. aaron Avatar
    aaron

    are there permissions that need to be added to the manifest?

  18. imsuperdumm Avatar
    imsuperdumm

    can anyone tell me…, what does ht.put(“var1″,”val1”); mean?
    especially the var1 & val1…
    are they the parameters that we use to call in php file?

    thanks

  19. imsuperdumm Avatar
    imsuperdumm

    why does the compiler always prompt debug perspective?
    is there something wrong?

  20. imsuperdumm Avatar
    imsuperdumm

    I have no idea…, where do you plan to send the file?
    do you want to do write bytes to mysql table?
    or just send it to server folder…?
    cause i’ve click for 100 times and it does nothing but
    debug perspective….

  21. imsuperdumm Avatar
    imsuperdumm

    excuse me Moazzam, can I get the php code?
    it’s to store to BLOB table…
    cause it’s always 0Bytes in my table
    thank you

  22. imsuperdumm Avatar
    imsuperdumm

    now, it’s 20 Bytes…and when I export it to .xls file it contains string of file path
    like “/sdcard/himalaya.jpg” and still not the file…
    how?

  23. imsuperdumm Avatar
    imsuperdumm

    thanks Moazzam! your code works!
    but still 0 Bytes in my BLOB…
    I know it works because when I open the task manager…
    it shows amounts of Bytes that have been sent through the internet
    and those bytes (when I calculate) have total size
    roughly same with the image size in my emulator sdcard
    same story happened when I change the file with different size…

    I guess I have problems with my php code…

    last thing i want to know is “do you send the image file in binary representation or else?” cause it will really helps me to make suitable php file to receive the data….
    then, if you send it in binary do i need to convert it to hexadecimal before insert it to my BLOB table?

    really thanks!!! I’m attending an android competition now…
    that’s why i’m really frustrated!!!

  24. Moazzam Avatar

    Hi imsuperdumm,

    Try this link http://www.php.net/manual/en/features.file-upload.post-method.php

    It talks about how to handle file uploads using PHP. Please let me know how your project goes (and what it’s about) when you can, if you don’t mind sharing.

  25. imsuperdumm Avatar
    imsuperdumm

    Hi Moazzam,

    my project is about an android shop app. it works just like ebay…
    with shop maps and nearest route to the shop…
    the user can upload their goods images, their place address, and price…
    if someone wants to seek for a product or particular thing…
    it will display the categories that related to their search

    i’ve done in signup and signin user by store their account details on mysql server.

    anyway, i’m already lost…
    not because the code…, the proposal is just not so good…
    (what a silly competition)

    o yea…, i’m planning to make the vid tutorial about this code…(if it works to me one day) on youtube…
    would you permit it, Moazzam?

    btw thnx Moazzam…! I hope U will make more android tutorials!
    have a nice day!!!

  26. Moazzam Avatar

    Hi imsuperdumm,

    That sounds like an interesting project. Best of luck with it. A video tutorial sounds good. Please let me know when you make it. I will put it up on my blog, too.

    And, thanks for the encouragement on making tutorials ๐Ÿ˜€

    Regards,
    Moazzam

  27. Umar Avatar
    Umar

    moazzam i am using your code and it works fine if image size is upto 2 mb or in some cases upto 4-5 mbs
    then it take so much time to upload image

    any idea to decrease size or make image upload faster?
    or any other suggestion?

    waiting for your reply.
    Umar

  28. Moazzam Avatar

    Hi Umar,

    I haven’t played around with the image manipulation library in Android but you should be able to find something to compress the image – maybe convert the image to a jpeg?

  29. Umar Avatar
    Umar

    can you please guide how to use progress bar to show upload progress in this tutorial?

    and which is suitable way to upload files? background service or normal thread?

  30. Sami Abu-El-Haija Avatar
    Sami Abu-El-Haija

    This is a fine piece of art.

    What is the license on this code if I want to use it?

    Thanks!

  31. Aysle Avatar
    Aysle

    Im wondering why you have

    Log.e(“ERROR”, line);

    in public static HttpData post(String sUrl, String data) {

    it always throws an error for me…

  32. neil Avatar
    neil

    Hi moazzam,

    I’m new to android as well as java. I’m using Eclipse. I tried your code and added few lines so I can display it. However, the only string that is being shown is hello android and not the data.content. What is wrong with my code?

    The full code
    http://www.pastie.org/1641261

    The code I added to call your function

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* pull a webpage
    *
    */
    HttpData data = HttpRequest.get(“http://www.pgts.com.au/download/txt/wav.txt”);
    System.out.println(data.content); /* <—- this is not displayed on my phone */

    /* added the lines below to test if this procedure is being called and yes it does because
    hello android is displayed. Not sure why "data.content" is not being displayed
    */
    TextView tv = new TextView(this);
    tv.setText("hello android"); /* <—- I can see this in my phone */
    setContentView(tv);
    }

  33. Moazzam Avatar

    Hi Aysle,

    Thanks for letting me know about that. I removed it so it shouldn’t bother you anymore ๐Ÿ™‚

  34. ASHISH PRAKASH Avatar
    ASHISH PRAKASH

    i want to know what this code exactly do after submittng the form… like if i submit the form, what type of data it takes from the server… can u explain me with a example…. i m a newbie

  35. Moazzam Avatar

    Hi Ashish,

    This library will post whatever you tell it to post. The server side code is out of the scope of this library ๐Ÿ™‚

  36. kumar Avatar
    kumar

    i am new to android,i am unable to unstand the flow and it shows the errors on myeclipse,how to call
    HttpData and HttpRequest class in main activity

  37. Moazzam Avatar

    Hi Kumar,

    You have to save both classes (if you don’t know where then put them in the same folder as your main activity) and type this at the top of you main activity file:

    import moz.http.*;
    

    Wherever you want to make an HTTP request, just follow the usage examples I have in the comments of the HttpRequest class.

  38. JDoe Avatar
    JDoe

    How should we run this code so that it doesn’t block UI thread? Do we start it inside a normal thread or should we do it in Asynctask etc? What about orientation changes? How are you yourself running this?

  39. Nizam Avatar
    Nizam

    Hi Moazzam,

    Thanks for putting this useful code. A few things though:

    1) Due to your code block display above, triple double quotes are bot escaped correctly. If you copy from here to Eclipse, you will see those errors. E.g.: #214, there are a few more like this.
    2) Also, there are many warnings in Eclipse.

    Thanks

  40. Prateek Avatar
    Prateek

    Hi Moazzam,

    Can you tell me how can this code help in image uploading on android with the proper UI attached.

  41. Moazzam Avatar

    The library doesn’t care about the UI. You just have to provide it the parameters it needs and it will do what it is supposed to. The UI is something you will have to code ๐Ÿ™‚

  42. Jemli Avatar

    Thks dude for the code. it reelly helped me in my project. ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *