I really see much better having a RestClient class in order to have more code scalability,but basically I think your code is good, for basic solutions.Here I post a proper RestClient class, wich implements a POST or a GET:
public class RestClient {
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String url;
private String response;
private int responseCode;
public String GetResponse()
{
return response;
}
public int GetResponseCode()
{
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestType requestType) throws Exception
{
switch(requestType)
{
case GET:
{
String combinedParams = "";
if (!params.isEmpty())
{
combinedParams += "?";
for (NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if (combinedParams.length() > 1)
combinedParams += "&" + paramString;
else
combinedParams += paramString;
}
}
HttpGet request = new HttpGet(url + combinedParams);
for (NameValuePair h: headers)
request.addHeader(h.getName(),h.getValue());
ExecuteRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
for (NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
ExecuteRequest(request, url);
break;
}
}
}
public void ExecuteRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try
{
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream in = entity.getContent();
response = ConvertStreamToString(in);
in.close();
}
}
catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
Log.e("REST_CLIENT", "Execute Request: " + e.getMessage());
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private String ConvertStreamToString(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
Log.e("REST_CLIENT", "ConvertStreamToString: " + e.getMessage());
e.printStackTrace();
}
}
return sb.toString();
}
With this you can easily do a POST like this, for example:
RestClient rest = new RestClient(url)
rest.addHeader(h.name,h.value);
rest.Execute(RequestType.POST);