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

自己的一點小結,希望對遇到相同問題的人有幫助。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *