Angel Arcoraci

Microsoft Student Partner – Mza – Arg

Android WCF REST requests made simple (using JSON)

I’ve been struggling for some time trying to get my Android phone to talk with a WCF REST web service. Finally I was able to do it and I decided to share the knowledge.

A few things to consider first:

  1. I gave up trying to make it work using XML but I like JSON anyway. If you manage to get this working using xml headers please comment !
  2. The response is not even ready yet, I just got excited I got this working. I’ll post an update later doing a JSON parsing of the response.
  3. The C# WCF REST web service was built using the Online Pattern and not the default one: new project –> online templates –> WCF –> WCF REST Service Template 40(CS)
  4. The Operation Contracts are tagged to use JSON:
    [OperationContract]
    [WebInvoke(UriTemplate = "ValidateCredentials",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        Method = "POST",
        RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
    string ValidateCredentials(string username, string password);

About the Android code:

I want to stress that this is just a quick example of how I made it work, avoid making comments about the quality of the code please ! Sonrisa

Notice I’ve obscured the IP address and port. Change that to suit your needs.

Also, I’m using a singleton pattern, you can avoid that too if you want to.

import java.io.IOException;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;

public final class RestClient {

private static final String URL = “http://XXX.XXX.XXX.XXX:YYYY/AccountServices/ValidateCredentials”;

private static RestClient instance = new RestClient();

public static RestClient getInstance() {
return instance;
}

private RestClient() {

}

public JSONObject sendJson(ArrayList<NameValuePair> params) {
JSONObject result = null;

HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;

JSONObject json = new JSONObject();

try {
HttpPost post = new HttpPost(URL);

for (NameValuePair p : params){
json.put(p.getName(), p.getValue());
}

StringEntity se = new StringEntity(json.toString());

post.setEntity(se);
post.setHeader(“Accept”, “application/json”);
post.setHeader(“Content-type”, “application/json”);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
}
} catch (JSONException ex) {

} catch (UnsupportedEncodingException ex) {

} catch (ClientProtocolException ex) {

} catch (IOException ex) {

}

return result;
}

}

The problem I originally had were the headers ! I was getting “bad request” all the time. Seems the process of setting the headers on the HttpPost object is very precise.

To finish the example, this is how you make a call:

ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "username value"));
params.add(new BasicNameValuePair("password", "password value"));

RestClient.getInstance().sendJson(params);

The ideal scenario should be to have an URL as a parameter too. I’ll add that on a second update regarding this topic.

Again, I’m not doing anything with the response !!! Actually I don’t even know how I’ll work that out, but should be fairy simple from here.

Bests,

Angel

Advertisement

Deja un comentario

Fill in your details below or click an icon to log in:

Logo de WordPress.com

You are commenting using your WordPress.com account. Log Out / Cambiar )

Twitter picture

You are commenting using your Twitter account. Log Out / Cambiar )

Facebook photo

You are commenting using your Facebook account. Log Out / Cambiar )

Connecting to %s

Seguir

Get every new post delivered to your Inbox.