In my android app, I tried to send a POST request to Google Forms, but an error 400 is returned:
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
....
Here is my code:
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>
}
Usage:
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))
Note that the json object has the key-value format like: {"entry.xxxxx1":"Test"}
Does anyone have an idea why this error code is returned? Has anyone successfully sent a POST to a Google Form in Android?
Thanks.
I have made the following modifications, and the code is now able to post to Google forms:
In the FormApi:
POST("{key}/formResponse")
@FormUrlEncoded
fun formResponse(@Path("key") key: String, @FieldMap hashmap: HashMap<String, Any>): Call<ResponseBody>
Usage:
val call = api.formResponse(key, hash)
where "hash" is a HashMap with the actual values of the fields (not URLEncoded)