【问题标题】:How to solve date format exception in Okhttp?如何解决 Okhttp 中的日期格式异常?
【发布时间】:2020-03-04 17:31:08
【问题描述】:

当我尝试在邮递员中使用某些参数访问 POST API 时,我得到 200 当我尝试使用 Retrofit 使用某些参数访问 POST API 时,我得到 417

例外:Invalid datetime format: 7 ERROR: invalid input syntax for type date: "null"

 `Invalid datetime format: 7 ERROR:  invalid input syntax for type date: "null"`

【问题讨论】:

  • 为什么你使用两个 hasmap 只使用一个具有不同值和键的,并告诉我你的邮递员如何发送数据
  • API 中的日期格式是什么?
  • @Amitpandey { "body": { "sex_id": null, "appointment_statudid": null, "mpi": "", "appointmentfromdate": "2020/02/28", "appointmenttodate" : "2020/02/28", "insuranceType": null } }
  • @VishalBhut 我不知道

标签: android


【解决方案1】:
 @POST("your api site")
fun sendData(@QueryMap hashMap: Map<String, String>): Call<ApiResponse<Any>>

为此制作一个hasmap

Hashmap<String,String> hashMap = HashMap<String, String>()
    hashMap["sex_id"] = sexid
    etc

【讨论】:

  • 你能用java/做吗
  • 但有些值或整数和字符串
  • 比使用 jsonobject 并转换成 int 和 string 并传递它
  • 是什么意思?它说的是预期的 BEGIN_OBJECT,但在第 1 行第 1 列路径上是 STRING
  • HashMap yourHash = new HashMap(); yourHash.put("消息","消息"); yourHash.put("时间戳",timestamp); yourHash.put("count",count); yourHash.put("版本",版本);
【解决方案2】:
String dtStart = "2020/02/28";  
Date date;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");  
try {  
    date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

这样写日期

data.put("date_of_birth", date);

【讨论】:

    【解决方案3】:

    您必须添加 Date 对象而不是 String。并且还在您的 Retrofit 构建器设置中添加 Gson converterFactory 和日期模式:

    Retrofit.Builder()
                .addConverterFactory(gsonConverterFactory)
    
     gsonConverterFactory = GsonConverterFactory.create(GsonBuilder()
                    .setDateFormat(SERVER_DATE_PATTERN)
                    .serializeNulls()
                    .create())
    

    然后像这样发布:

    @POST("api.....")
    Call<Response> validateRegistrationCredentials(@Body YourPostBodyModel body);
    
    class YourPostBodyModel {
      Date bithday;
      ......
    }
    

    【讨论】:

    • 等等,别去任何地方让我试试
    • 您应该会看到您在 Android Studio LogCat 中发布了正文。你发帖正确吗?使用身体模型?和@Post 注释?
    • 是的,我看到了。它运行正常。如果我使用 JSONObject.NULL,它不会进入正文,并且 417 表示缺少必需的 propertydate_of_birth
    • 所以如果错误来自服务器而不是改造,那么您可能只是使用了错误的日期格式
    • 但我该如何解决?在邮递员中看到,我传递了 null 并且我得到了正确的响应
    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2013-06-03
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多