Monday 2 April 2012

How to call a restful web service from android .


In this post i have explained " How to call a restful web service from android" using DefaultHttpClient
from android.




String loginurl="restful service url";

public String authenticate(String userName, String passWord,
String clientName) throws JSONException, IllegalStateException,
IOException {

HttpPost request = new HttpPost(loginurl);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONObject json = new JSONObject();
json.put("UserName", userName);
json.put("Password", passWord);
json.toString();
JSONStringer str = new JSONStringer().object().key("clientEntity")
.value(json).endObject();
StringEntity entity = new StringEntity(str.toString());
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Log.e("Status code ", "status code is " + response.getStatusLine());
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int) responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
String response_str = new String(buffer);
int i = response.getStatusLine().getStatusCode();
if (i == 200) {
Log.d("output authenticate method", response_str);
return response_str;
} else {
response_str = Integer.toString(i);
return response_str;
}
}


i called wcf in this example:

[OperationContract]
        [WebInvoke(RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest,
           UriTemplate = "/uritemplate")]
        bool ValidateMobileUser(MobileClientEntity clientEntity);


No comments:

Post a Comment