Saturday, February 11, 2012

How to send HTTP Requests with Java API (URLConnection)


A simple class for sending HTTP requests like GET or POST. Uses the standard Java API (URLConnection). Android 2.2 has a bug with this API. This class solves the bug. You can add more functionalities getting response details.
Look here if you want to see the same class but using Apache HttpComponents API.
Usage: Note: You should execute this class within a secondary thread, never is the main thread (UI thread)
HttpRequest request = new HttpRequest ("http://localhost/path", HttpRequest.GET); request.addParameter ("param1", "value1").addParameter ("param2", "value2"); request.send (); request.getResponseAsString(); InputStream in = request.getResponseAsStream (); if (in != null){ ... //Remember to close stream in.close (); }
//You can reuse a request request.clearParameters (); request.addParameter ("param3", "value3"); int code = request.getResponseCode (); if (code == -1) //a request has not been sended if (code == 200) //ok
//Remember to disconnect on finish request.disconnect ();
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

public class HttpRequest{
public static final String GET = "GET";
public static final String POST = "POST";
private String method;
private String url;
private ArrayList<NameValuePair> params;
private InputStream in;
private int httpCode;
private int length;
private HttpURLConnection con;
private class NameValuePair{
String name;
String value;
NameValuePair (String name, String value){
this.name = name;
this.value = value;
}
}
public HttpRequest (String url, String method){
this.url = url;
this.method = method;
params = new ArrayList<NameValuePair> ();
httpCode = -1;
length = -1;
}

public HttpRequest setUrl (String url){
this.url = url;
return this;
}
public String getUrl (){
return url;
}
public HttpRequest setMethod (String method){
this.method = method;
return this;
}

public String getMethod (){
return method;
}
public HttpRequest addParameter (String name, Object value){
params.add (new NameValuePair (name, value.toString ()));
return this;
}

public HttpRequest addParameters (String[] names, Object[] values){
int len = names.length;
if (len == values.length){
for (int i=0; i<len; i++){
addParam (names[i], values[i].toString ());
}
}
return this;
}

public HttpRequest replaceParameter (String name, Object value){
int len = params.size ();
NameValuePair pair;
for (int i=0; i<len; i++){
pair = params.get (i);
if (pair.name.equals (name)){
pair.value = value.toString ();
break;
}
}
return this;
}

public HttpRequest clearParameters (){
params.clear ();
return this;
}
public void send () throws MalformedURLException, SocketTimeoutException, ProtocolException, IOException{
int len = params.size ();
if (len == 0) return;
//Fix for android 2.2
URL oldUrl = new URL (url);
NameValuePair pair;
String query = "";
for (int i=0; i<len; i++){
pair = params.get (i);
query += pair.name + "=" + pair.value;
if (i != len - 1) query += "&";
}
//Desconecto una posible peticion anterior
if (con != null) con.disconnect ();
in = null;
httpCode = -1;
length = -1;
String file = oldUrl.getFile ();
//Fix for android 2.2
if (method.equals (GET)) file += "?" + query;
URL u = new URL (oldUrl.getProtocol (), oldUrl.getHost (), oldUrl.getPort (), file);
con = (HttpURLConnection)u.openConnection ();
con.setRequestMethod (method);
con.setDoInput (true);
if (method.equals (POST)){
con.setDoOutput (true);
DataOutputStream out = new DataOutputStream (con.getOutputStream ());
out.writeBytes (query);
out.flush ();
out.close ();
}
in = new BufferedInputStream (con.getInputStream ());
httpCode = con.getResponseCode ();
if (httpCode != 200){
in.close ();
in = null;
}
length = con.getContentLength ();
}
public void disconnect (){
if (con != null){
con.disconnect ();
con = null;
}
}
public String getResponseAsString () throws IOException{
if (in != null){
StringBuilder builder = new StringBuilder();
String line; 
try{
BufferedReader reader = new BufferedReader (new InputStreamReader (in, "UTF-8"));
while ((line = reader.readLine ()) != null) {
builder.append (line);
}
}finally{
in.close ();
}
return builder.toString ();
}
return null;
}

public InputStream getResponseAsStream (){
return in;
}

public int getResponseCode (){
return httpCode;
}

public int getContentLength (){
return length;
}
}

No comments:

Post a Comment