Android向Rest服務Post資料遇到的Date類型資料問題

來源:互聯網
上載者:User

 今天在Android端向Rest服務Post資料時,總是不成功,查了很多資料,才知道Rest端將json串還原序列化時,需要的時間格式必須是UTC類型,及Date(12345678+0800)格式。 Android端序列化方法  複製代碼//利用Gson實現對象序列化為Jsonpublic 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);自己的一點小結,希望對遇到相同問題的人有協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.