将POST请求发送到Google表单会返回代码400

时间:2019-03-17 05:48:18

标签: android rest google-api retrofit2 google-form

在我的Android应用中,我尝试将POST请求发送到Google Forms,但返回了错误400:

400 https://docs.google.com/forms/d/e/[form-id-number-here]/formResponse (114002ms)
content-type: text/html; charset=utf-8
x-robots-tag: noindex, nofollow, nosnippet
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: Mon, 01 Jan 1990 00:00:00 GMT
date: Sun, 17 Mar 2019 05:03:05 GMT
p3p: CP="This is not a P3P policy! See g.co/p3phelp for more info."
p3p: CP="This is not a P3P policy! See g.co/p3phelp for more info."
x-chromium-appcache-fallback-override: disallow-fallback
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
server: GSE
....

这是我的代码:

interface FormApi {
    @Headers("Content-Type: application/json",  "Accept: text/html", "Cache-Control: no-cache")
    @POST("{key}/formResponse")
    fun formResponseJson(@Path("key") key: String, @Body json: JsonObject): Call<ResponseBody>

}

用法:

val gson = GsonBuilder().setLenient().create()
val client = OkHttpClient.Builder()
            .readTimeout(timeout.toLong(), TimeUnit.SECONDS)
            .connectTimeout(timeout.toLong(), TimeUnit.SECONDS)
            .build()
val retrofit = Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client)
            .build()
val api = retrofit.create(FormApi::class.java)
val json = dataObj.toJson()
val call = api.formResponseJson(key, json)
call.enqueue(CallBackResult(resultReceiver))   

请注意,json对象的键值格式如下:{“ entry.xxxxx1”:“ Test”}

有人知道为什么会返回此错误代码吗?是否有人成功将POST发送到Android中的Google表单?

谢谢。

1 个答案:

答案 0 :(得分:0)

我进行了以下修改,并且代码现在可以发布到Google表单:

在FormApi中:

    POST("{key}/formResponse")
    @FormUrlEncoded
    fun formResponse(@Path("key") key: String,  @FieldMap hashmap: HashMap<String, Any>): Call<ResponseBody>

用法:

val call = api.formResponse(key, hash)

其中“哈希”是具有字段实际值的HashMap(未经URLEncoded)