我有一个WCF restful服务,因为我有一个POST方法。从android客户端调用它时,参数对象在WCF方法上始终为null。下面是android和WCF服务的代码。
WCF接口:
[OperationContract(Name = "datetime1")]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "datetime1", BodyStyle = WebMessageBodyStyle.Wrapped)]
ResponseMessage GetResponse(RequestData req);
WCF方法实施:
public ResponseMessage GetResponse(RequestData req)
{
string s = req == null ? "Yes" : "No";
ResponseMessage msg = new ResponseMessage()
{
DateTime = DateTime.Now.ToShortDateString(),
Error = "none",
hoursLeft = 5,
IsTrialExpired = false,
Response = "My Response " + s,
token = "token here"
};
return msg;
}
Android客户端,调用代码:
RequestData requestData = new RequestData("1","2","3","4");
JSONStringer req = new JSONStringer();
try {
req.object()
.key("UserId").value(requestData.getUserId())
.key("AppId").value(requestData.getAppId())
.key("ThirdParty").value(requestData.getThirdParty())
.key("UserToken").value(requestData.getUserToken())
.endObject();
} catch (JSONException e) {
e.printStackTrace();
}
String url = "<my method url>";
//instantiates httpClient to make request
HttpClient httpClient = new DefaultHttpClient();
//url with the post data
HttpPost httPost = new HttpPost(url);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(req);
//sets the post request as the resulting string
httPost.setEntity(se);
httPost.setHeader("Accept", "application/json");
httPost.setHeader("Content-type", "application/json");
HttpResponse httpresponse = httpClient.execute(httPost);
InputStream inputStream = httpresponse.getEntity().getContent();
if (inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null)
res += line;
inputStream.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
请求JSon:
{"UserId":"1","AppId":"2","ThirdParty":"3","UserToken":"4"}
回应JSon:
{"datetime1Result":{"DateTime":"7\/31\/2014","Error":"none","IsTrialExpired":false,"Response":"My Response Yes","hoursLeft":5,"token":"token here"}}
注意:注意响应字符串中的“是”,这是因为对象为空。
我的RequestData类:
[DataContract]
public class RequestData
{
[DataMember]
public string UserId { get; set; }
[DataMember]
public string AppId { get; set; }
[DataMember]
public string ThirdParty { get; set; }
[DataMember]
public String UserToken { get; set; }
}
我做错了什么???
答案 0 :(得分:0)
更改JSONStringer的引用名称。 JSONStringer和StringEntity的引用名称(req)都相同