Search code examples
javaandroidgoogle-formsokhttp

OKHTTP3 POST FORM android application doesn't post anything to Google Forms


I've read and understood the following code from this web page as a reference to developing my android application: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostForm.java

public class PostForm extends AsyncTask<String, Void, String>
{
     public static final MediaType FORM_DATA_TYPE = MediaType.parse("application/text; charset=utf-8");

     String URL = "https://docs.google.com/forms/d/e/FILLERFORMTESTINGNOTREAL";
     String USER_NAME = "entry.XXXXXXXXX"; //FAKE ENTRY
     String PASSWORD = "entry.XXXXXXXXX"; //FAKE ENTRY

@Override
public String doInBackground(String... params)
{
    String username = params[0];
    String password = params[1];

    try
    {
        OkHttpClient client = new OkHttpClient();

        String post_data = USER_NAME + "=" + URLEncoder.encode(username, "UTF-8") +
                "&" + PASSWORD + "=" + URLEncoder.encode(password, "UTF-8");

        RequestBody requestBody = RequestBody.create(FORM_DATA_TYPE, post_data);

        Request request = new Request.Builder()
                .url(URL)
                .post(requestBody)
                .build();

        client.newCall(request).execute();

    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return null;

}

What am I doing wrong? The android application appears to successfully submit data, but when I check the Google Form, no data is entered?... Please help!


Solution

  • I was using RequestBody when I should have been using FormBody...

                FormBody formBody = new FormBody.Builder()
                    .add(USERNAME, usr)
                    .add(PASSWORD, pwd)
                    .build();
    

    Whoops! Now the program works lol