Moazzam's Ramblings

18Nov/0942

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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<String> keys = dat.cookies.keys(); // cookies
* while (keys.hasMoreElements()) {
* 		System.out.println(keys.nextElement() + " = " +
* 				data.cookies.get(keys.nextElement() + "rn");
*	}
* Enumeration<String> keys = dat.headers.keys(); // headers
* while (keys.hasMoreElements()) {
* 		System.out.println(keys.nextElement() + " = " +
* 				data.headers.get(keys.nextElement() + "rn");
*	}
*
* Upload a file
* --------------------------------
* ArrayList<File> files = new ArrayList();
* files.add(new File("/etc/someFile"));
* files.add(new File("/home/user/anotherFile"));
*
* Hashtable<String, String> ht = new Hashtable<String, String>();
* 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<String, List<String>> headers = con.getHeaderFields();
                        Set<Entry<String, List<String>>> hKeys = headers.entrySet();
                        for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
                                Entry<String, List<String>> 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<String, String> ht) throws Exception {
                String key;
                StringBuffer data = new StringBuffer();
                Enumeration<String> 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("&amp;");
                }
                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<String, List<String>> headers = conn.getHeaderFields();
                        Set<Entry<String, List<String>>> hKeys = headers.entrySet();
                        for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
                                Entry<String, List<String>> 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<File> files)
        {
                Hashtable<String, String> ht = new Hashtable<String, String>();
                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<String, String> params, ArrayList<File> 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<files.size(); i++) {
                                Log.i("HREQ", i+"");
                                FileInputStream fis = new FileInputStream(files.get(i));
                                dos.writeBytes("--" + boundary + newLine);
                                dos.writeBytes("Content-Disposition: form-data; "
                                + "name="file_"+i+"";filename=""
                                + files.get(i).getPath() +""" + newLine + newLine);
                                bytesAvailable = fis.available();
                                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                byte[] buffer = new byte[bufferSize];
                                bytesRead = fis.read(buffer, 0, bufferSize);
                                while (bytesRead > 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<String, List<String>> headers = con.getHeaderFields();
                        Set<Entry<String, List<String>>> hKeys = headers.entrySet();
                        for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
                                Entry<String, List<String>> 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:

1
2
3
4
5
6
7
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) Trackbacks (0)
  1. Hi I didn’t find any HttpData Class in the documentation. Do you have a separate class for that?

  2. 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. 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. 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. Someone stole your code: sanderborgman.nl/android/android-httprequest-class/

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

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

  7. Missing backslashes:

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

    should be

    String newLine = “\r\n”;

  8. Also, thanks :) Code works!

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

  10. 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. 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 :D

  12. 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. 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. 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. 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. 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. are there permissions that need to be added to the manifest?

  18. 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. why does the compiler always prompt debug perspective?
    is there something wrong?

  20. 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. 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. 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. 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. 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. 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. 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 :D

    Regards,
    Moazzam

  27. 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. 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. 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. This is a fine piece of art.

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

    Thanks!

  31. 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. 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. Hi Aysle,

    Thanks for letting me know about that. I removed it so it shouldn’t bother you anymore :)

  34. 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. 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. 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. 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. 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. 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. Hi Moazzam,

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

  41. 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. Thks dude for the code. it reelly helped me in my project. :)


Leave a comment

No trackbacks yet.