Android向Rest服务Post数据遇到的Date类型数据问题
2014-03-13 19:53
435 查看
今天在Android端向Rest服务Post数据时,总是不成功,查了很多资料,才知道Rest端将json串反序列化时,需要的时间格式必须是UTC类型,及Date(12345678+0800)格式。
Android端序列化方法
Android端Post方法
C#Rest服务端
自己的一点小结,希望对遇到相同问题的人有帮助。
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);
自己的一点小结,希望对遇到相同问题的人有帮助。
相关文章推荐
- 使用Navicat Premium将Oracle数据库中的表和数据迁移到MySQL数据库中,遇到的Date类型出现精度问题及解决方法
- android POST数据遇到的UTF-8编码(乱码)问题解决办法
- Android的okhttp的post请求,php返回json数据。以及遇到的okhttp dispatcher问题,和json解析遇到的问题
- 关于在用curl函数post网页数据时,遇上表单提交 type为submit 类型而且没有name和id时可能遇到的问题及其解决方法
- Android Post Json数据乱码问题
- Android的Sqlite中DateTime类型数据的存取问题
- iOS开发中解析JSON中的boolean类型的数据遇到的问题
- hibernate 中使用oracle数据库 与java Date数据类型 只显示到天 不显示时分秒的问题
- WCF+Restfull服务 提交或获取数据时数据大小限制问题解决方案
- 使用Mysql遇到的几个数据类型/格式的问题
- Android的Sqlite中DateTime类型数据的存取问题
- date类型数据格式问题
- java 基本数据类型不常遇到的问题
- matlab数据类型转换遇到问题,及解决办法,sym,double ,vpa转换
- 关于myBatis与SQLserver 配合使用,查询类型为Date的数据时,日期会减少两天的问题
- Android RecyclerView经常遇到不能显示数据或只显示一行数据的问题
- 10月14日遇到的问题 在将 nvarchar 值 转换成数据类型 int 时失败。
- Android ListView的中的数据更新时遇到的一些问题的总结
- 总结一下基础和我遇到的问题 (关键字 -- 数据类型)
- SoapUI进行REST请求,POST方法提交到数据库的数据乱码问题