• 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);

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

  • 相关阅读:
    yml 配置文件注入
    STS 自动生成 getter 和 setter
    maven build 失败
    navicat 使用
    STS 设置 注解提示
    windows下安装Mysql
    安装 mysql
    用Navicat Premium 操作MySQL数据库
    渐变显示渐变消失的BackgroundView
    基于dispatch_after封装YXTimer
  • 原文地址:https://www.cnblogs.com/yyx03/p/3599227.html
Copyright © 2020-2023  润新知