/[aagtl_public1]/src/moz/http/HttpRequest.java
aagtl

Contents of /src/moz/http/HttpRequest.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3 - (show annotations) (download)
Sun Aug 5 14:00:28 2012 UTC (11 years, 7 months ago) by zoffadmin
File size: 9878 byte(s)
license text correction
1 /**
2 * aagtl Advanced Geocaching Tool for Android
3 * loosely based on agtl by Daniel Fett <fett@danielfett.de>
4 * Copyright (C) 2010 - 2012 Zoff <aagtl@work.zoff.cc>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * version 2 as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the
17 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
19 */
20
21 package moz.http;
22
23 import java.io.BufferedReader;
24 import java.io.DataOutputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStreamWriter;
29 import java.net.HttpURLConnection;
30 import java.net.MalformedURLException;
31 import java.net.URL;
32 import java.net.URLConnection;
33 import java.net.URLEncoder;
34 import java.util.ArrayList;
35 import java.util.Enumeration;
36 import java.util.Hashtable;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.Set;
42
43 import android.util.Log;
44
45 /**
46 * HTTP Request class
47 *
48 * You can use this class and distribute it as long as you give proper credit
49 * and place and leave this notice intact :). Check my blog for updated
50 * version(s) of this class (http://moazzam-khan.com)
51 *
52 * Usage Examples:
53 *
54 * Get Request
55 * --------------------------------
56 * HttpData data = HttpRequest.get("http://example.com/index.php?user=hello");
57 * System.out.println(data.content);
58 *
59 * Post Request
60 * --------------------------------
61 * HttpData data = HttpRequest.post("http://xyz.com", "var1=val&var2=val2");
62 * System.out.println(data.content);
63 * Enumeration<String> keys = dat.cookies.keys(); // cookies
64 * while (keys.hasMoreElements()) {
65 * System.out.println(keys.nextElement() + " = " +
66 * data.cookies.get(keys.nextElement() + "rn");
67 * }
68 * Enumeration<String> keys = dat.headers.keys(); // headers
69 * while (keys.hasMoreElements()) {
70 * System.out.println(keys.nextElement() + " = " +
71 * data.headers.get(keys.nextElement() + "rn");
72 * }
73 *
74 * Upload a file
75 * --------------------------------
76 * ArrayList<File> files = new ArrayList();
77 * files.add(new File("/etc/someFile"));
78 * files.add(new File("/home/user/anotherFile"));
79 *
80 * Hashtable<String, String> ht = new Hashtable<String, String>();
81 * ht.put("var1", "val1");
82 *
83 * HttpData data = HttpRequest.post("http://xyz.com", ht, files);
84 * System.out.println(data.content);
85 *
86 * @author Moazzam Khan
87 */
88 public class HttpRequest
89 {
90
91 /**
92 * HttpGet request
93 *
94 * @param sUrl
95 * @return
96 */
97 public static HttpData get(String sUrl)
98 {
99 HttpData ret = new HttpData();
100 String str;
101 StringBuffer buff = new StringBuffer();
102 try
103 {
104 URL url = new URL(sUrl);
105 URLConnection con = url.openConnection();
106
107 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
108 while ((str = in.readLine()) != null)
109 {
110 buff.append(str);
111 }
112 ret.content = buff.toString();
113 //get headers
114 Map<String, List<String>> headers = con.getHeaderFields();
115 Set<Entry<String, List<String>>> hKeys = headers.entrySet();
116 for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();)
117 {
118 Entry<String, List<String>> m = i.next();
119
120 Log.w("HEADER_KEY", m.getKey() + "");
121 ret.headers.put(m.getKey(), m.getValue().toString());
122 if (m.getKey().equals("set-cookie")) ret.cookies.put(m.getKey(), m.getValue().toString());
123 }
124 }
125 catch (Exception e)
126 {
127 Log.e("HttpRequest", e.toString());
128 }
129 return ret;
130 }
131
132 /**
133 * HTTP post request
134 *
135 * @param sUrl
136 * @param ht
137 * @return
138 * @throws Exception
139 */
140 public static HttpData post(String sUrl, Hashtable<String, String> ht) throws Exception
141 {
142 String key;
143 StringBuffer data = new StringBuffer();
144 Enumeration<String> keys = ht.keys();
145 while (keys.hasMoreElements())
146 {
147 key = keys.nextElement();
148 data.append(URLEncoder.encode(key, "UTF-8"));
149 data.append("=");
150 data.append(URLEncoder.encode(ht.get(key), "UTF-8"));
151 data.append("&amp;");
152 }
153 return HttpRequest.post(sUrl, data.toString());
154 }
155
156 /**
157 * HTTP post request
158 *
159 * @param sUrl
160 * @param data
161 * @return
162 */
163 public static HttpData post(String sUrl, String data)
164 {
165 StringBuffer ret = new StringBuffer();
166 HttpData dat = new HttpData();
167 String header;
168 try
169 {
170 // Send data
171 URL url = new URL(sUrl);
172 URLConnection conn = url.openConnection();
173 conn.setDoOutput(true);
174 OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
175 wr.write(data);
176 wr.flush();
177
178 // Get the response
179
180 Map<String, List<String>> headers = conn.getHeaderFields();
181 Set<Entry<String, List<String>>> hKeys = headers.entrySet();
182 for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();)
183 {
184 Entry<String, List<String>> m = i.next();
185
186 Log.w("HEADER_KEY", m.getKey() + "");
187 dat.headers.put(m.getKey(), m.getValue().toString());
188 if (m.getKey().equals("set-cookie")) dat.cookies.put(m.getKey(), m.getValue().toString());
189 }
190 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
191 String line;
192 while ((line = rd.readLine()) != null)
193 {
194 ret.append(line);
195 }
196 Log.e("ERROR", line);
197 wr.close();
198 rd.close();
199 }
200 catch (Exception e)
201 {
202 Log.e("ERROR", "ERROR IN CODE:" + e.getMessage());
203 }
204 dat.content = ret.toString();
205 return dat;
206 }
207
208 /**
209 * Post request (upload files)
210 *
211 * @param sUrl
212 * @param files
213 * @return HttpData
214 */
215 public static HttpData post(String sUrl, ArrayList<InputStream> files, String c)
216 {
217 Hashtable<String, String> ht = new Hashtable<String, String>();
218 return HttpRequest.post(sUrl, ht, files, c);
219 }
220
221 /**
222 * Post request (upload files)
223 *
224 * @param sUrl
225 * @param params
226 * Form data
227 * @param files
228 * @return
229 */
230 public static HttpData post(String sUrl, Hashtable<String, String> params, ArrayList<InputStream> files, String this_cookie)
231 {
232 HttpData ret = new HttpData();
233 try
234 {
235 String boundary = "*****************************************";
236 boundary = "----------ThIs_Is_tHe_bouNdaRY_$";
237 String newLine = "\r\n";
238 int bytesAvailable;
239 int bufferSize;
240 int maxBufferSize = 4096;
241 int bytesRead;
242
243 URL url = new URL(sUrl);
244 HttpURLConnection con = (HttpURLConnection) url.openConnection();
245 con.setDoInput(true);
246 con.setDoOutput(true);
247 con.setUseCaches(false);
248 con.setRequestMethod("POST");
249 con.setRequestProperty("Cookie", this_cookie);
250 System.out.println("Cookie: " + this_cookie + ";");
251
252 con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
253 con.setRequestProperty("Pragma", "no-cache");
254 con.setRequestProperty("Connection", "Keep-Alive");
255 con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
256 DataOutputStream dos = new DataOutputStream(con.getOutputStream());
257
258 //dos.writeChars(params);
259
260 //upload files
261 for (int i = 0; i < files.size(); i++)
262 {
263 Log.i("HREQ", i + "");
264 InputStream fis = files.get(i);
265 dos.writeBytes("--" + boundary + newLine);
266 dos.writeBytes("Content-Disposition: form-data; " + "name=\"ctl00$ContentBody$FieldNoteLoader\"; filename=\"" + "geocache_visits.txt" + "\"" + newLine + newLine);
267 bytesAvailable = fis.available();
268 bufferSize = Math.min(bytesAvailable, maxBufferSize);
269 byte[] buffer = new byte[bufferSize];
270 bytesRead = fis.read(buffer, 0, bufferSize);
271 while (bytesRead > 0)
272 {
273 dos.write(buffer, 0, bufferSize);
274 bytesAvailable = fis.available();
275 bufferSize = Math.min(bytesAvailable, maxBufferSize);
276 bytesRead = fis.read(buffer, 0, bufferSize);
277 }
278 dos.writeBytes(newLine);
279 dos.writeBytes("--" + boundary + "--" + newLine);
280 fis.close();
281 }
282 // Now write the data
283
284 Enumeration keys = params.keys();
285 String key, val;
286 while (keys.hasMoreElements())
287 {
288 key = keys.nextElement().toString();
289 val = params.get(key);
290 dos.writeBytes("--" + boundary + newLine);
291 dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + newLine + newLine + val);
292 dos.writeBytes(newLine);
293 dos.writeBytes("--" + boundary + "--" + newLine);
294
295 }
296 dos.flush();
297
298 BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
299 String line;
300 while ((line = rd.readLine()) != null)
301 {
302 ret.content += line + "\r\n";
303 }
304 //get headers
305 Map<String, List<String>> headers = con.getHeaderFields();
306 Set<Entry<String, List<String>>> hKeys = headers.entrySet();
307 for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();)
308 {
309 Entry<String, List<String>> m = i.next();
310
311 Log.w("HEADER_KEY", m.getKey() + "");
312 ret.headers.put(m.getKey(), m.getValue().toString());
313 if (m.getKey().equals("set-cookie")) ret.cookies.put(m.getKey(), m.getValue().toString());
314 }
315 dos.close();
316 rd.close();
317 }
318 catch (MalformedURLException me)
319 {
320
321 }
322 catch (IOException ie)
323 {
324
325 }
326 catch (Exception e)
327 {
328 Log.e("HREQ", "Exception: " + e.toString());
329 }
330 return ret;
331 }
332 }

   
Visit the aagtl Website