zoukankan      html  css  js  c++  java
  • Android向Rest服务Post数据遇到的Date类型数据问题

      今天在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);

    自己的一点小结,希望对遇到相同问题的人有帮助。

  • 相关阅读:
    同时实现同时只允许一个人登录系统 dodo
    比较C#中的readonly与const (转) dodo
    iframe,Frame中关于Session丢失的解决方法 dodo
    sqlserver数据库同步解决方案 dodo
    利用C#调用WINRAR实现压缩与解压 dodo
    .net打包自动安装数据库 dodo
    关于sqlserver packet size dodo
    真正生成高质量不变形缩略图片 dodo
    Datagrid列表控件使用 dodo
    NUnit学习之VS.net 2005篇(转) dodo
  • 原文地址:https://www.cnblogs.com/yyx03/p/3599227.html
Copyright © 2011-2022 走看看