Here is a class that can be used to make HTTP get and HTTP post requests. I haven’t commented everything but the usage should be pretty clear from the method signatures.
Note: This is for Android 1.5.
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;
public class HttpRequest {
/**
* HttpGet - doesn't read cookies
*
* @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);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((str = in.readLine()) != null) {
buff.append(str);
}
ret.content = buff.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 {
StringBuffer data = new StringBuffer();
Enumeration<String> keys = ht.keys();
while (keys.hasMoreElements()) {
data.append(URLEncoder.encode(keys.nextElement(), "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(ht.get(keys.nextElement()), "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<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.toString());
}
dat.content = ret.toString();
return dat;
}
}
You will also need this class along with it.
[java]
import java.util.Hashtable;
public class HttpData {
public String content;
public Hashtable
public Hashtable
}
[/java]
Leave a Reply