今天在Android端向Rest服务Post数据时,总是不成功,查了很多资料,才知道Rest端将json串反序列化时,需要的时间格式必须是UTC类型,及Date(12345678+0800)格式。
Android端序列化方法
//利用Gson实现对象序列化为Json
public static String toJson(Object object) {
GsonBuilder builder = new GsonBuilder();
// 不转换没有 @Expose 注解的字段
builder.excludeFieldsWithoutExposeAnnotation();
//对Date类型进行注册事件
builder.registerTypeAdapter(Date.class, new UtilDateSerializer());
Gson gson = builder.create();
return gson.toJson(object);
} class UtilDateSerializer implements JsonSerializer<Date> {
@Override
public JsonElement serialize(Date src, Type typeOfSrc,
JsonSerializationContext context) {
//拼凑UTC时间类型
return new JsonPrimitive("/Date(" + src.getTime()+ "+0800)/");
}
}
Android端Post方法
/**
* 通过POST方式发送请求
*
* @param url
* URL地址
* @param params
* 参数
* @return
* @throws Exception
*/
public String httpPost(String url, String json) throws Exception {
String response = null;
int timeoutConnection = 3000;
int timeoutSocket = 5000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
// 添加http头信息
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("User-Agent", "imgfornote");
httpPost.setEntity(new StringEntity(json,"UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
response = EntityUtils.toString(httpResponse.getEntity());
} else {
response = String.valueOf(statusCode);
}
return response;
}
C#Rest服务端
[OperationContract]
[WebInvoke(UriTemplate = "/yyxTest", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string MensarTest(XCJCQK model);
自己的一点小结,希望对遇到相同问题的人有帮助。