Reputation: 1661
I'm trying to contact a RESTful WCF POST web service from an android client which should pass some data in json format. I've already succesfully contacted a RESTful WCF GET web service, but I cannot figure out how the POST version works.
This is the android client piece of code which makes the call:
HttpPost request = new HttpPost(uri);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
/*... Building the NameValuePairs object ... */
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
/* ... handling the response ...*/
and this is the WCF web service code:
[WebInvoke(Method = "POST",
UriTemplate = "ServiceActivation",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string MyPostMethod();
public string MyPostMethod()
{
try
{
/*...*/
}
catch (Exception e)
{
/*...*/
}
}
In this way the android client succesfully contact the web service; but I don't know how to retrieve in the MyPostMethod the data passed from the android client. Something like this: MyPostMethod(string data) ends in a bad request from the android client.
So, what is the way to retrieve passed data in the web service?
Thanks in advance!
Upvotes: 0
Views: 5876
Reputation: 1374
I'm sorry. This isn't answered for me:
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
I am in a similar bind to what j0nSn0w was at 17 Jun and can only find this thread as a constructive pointer.
To keep the actual solution out of the ticket seems perverse.
Upvotes: 0
Reputation: 2688
Gson makes it quite easy to build json messages in Android.
LoginToWebSiteRequest loginToWebSiteRequest = new LoginToWebSiteRequest();// a pojo based on some json message
loginToWebSiteRequest.setEmail(email);
loginToWebSiteRequest.setPassword(password);
Gson gson = new Gson();
String json = gson.toJson(loginToWebSiteRequest,LoginToWebSiteRequest.class);
HttpPost httpPost = new HttpPost(loginUrl);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
Upvotes: 0
Reputation: 364279
You have to define data contract for your posted data - generally class or set of related classes which will be used to deserialize JSON message and use that class as input parameter. Here is example how to use data contracts without WCF service - it can help you to define correct contract for your message.
Edit:
I just noticed that you are posting url encoded values - that is not a JSON request and it has different content type: application/x-www-form-urlencoded
. JSON request for WCF is JSON passed in request content. Working with URL encoded requests in WCF is hard. This will change in Web API which has support for these requests.
Upvotes: 1