ともこ
ともこ

Reputation: 835

Parameter sent from android app by posting always be empty on backend server written in Go language

I am trying to post a token by using SendUserIdTokenToBackend() method in an android app.

private class SendUserIdTokenToBackend extends AsyncTask<String, Void, String> {

    private Exception exception;

    @Override
    protected String doInBackground(String... idToken) {
        Log.d(TAG, "idToken" + idToken);
        try {
            List<Pair> params = new ArrayList<Pair>();
            Pair<String, String> pair = Pair.create("idToken", idToken[0]);
            params.add(pair);
            String paramString = getQuery(params);

            URL url = new URL("http://itforhr.com/webservice/android-sign-in");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));

            writer.write(paramString);

            writer.flush();
            writer.close();
            os.close();

            Log.d(TAG, "getQuery:" + paramString);


            conn.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                stringBuilder.append(line + "\n");
            }

            return stringBuilder.toString();


        } catch (Exception e) {

            return  "Error sending ID token to backend. " + e.toString();
        }
    }

    @Override
    protected void onPostExecute(String result) {


        mIdTokenTextView.setText(getString(R.string.id_token_fmt, result));
    }
}


private String getQuery(List<Pair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (Pair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.first.toString(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.second.toString(), "UTF-8"));
    }

    return result.toString();
}

Log.d results are ok. I see token id printed correctly in the log.

However on the server side, I can't get idToken parameter

    func init() {
        http.HandleFunc("/webservice/android-sign-in/", androidSignInHandler)
    }

    func androidSignInHandler(w http.ResponseWriter, r *http.Request) {

        log.Println("(-------- Entering androidSignInHandler --------)")

        ctx := appengine.NewContext(r)

        idToken := r.FormValue("idToken")

        client := urlfetch.Client(ctx)
        _, err := client.Get("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + idToken)

        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        } else {

            w.Header().Set("Content-Type", "text/html")

            fmt.Fprintf(w, "%v and %v", r.PostForm, idToken)

        }

        log.Println("(-------- Exiting androidSignInHandler --------)")

    }

fmt printed out "map[] and",idToken is empty. I tried calling parseForm() before getting idToken parameter but it didn't work. I have been stuck here for two nights. Please help.

Upvotes: 0

Views: 50

Answers (1)

Andreas Schyman
Andreas Schyman

Reputation: 181

It looks like the handler in go should work, and also that the java code should send a proper request. Usually in these cases, it is useful to test the parts separately.

One way to test the server is to use curl to send a request to the server, as in

curl -v --data "idToken=theToken" http://itforhr.com/webservice/android-sign-in

and check if that works. If it works, then you know the problem is on the client side, if not, it is probably on the server side.

You could further check what the server is actually receiving by reading the body without parsing it:

b, _ := ioutil.ReadAll(r.Body)
fmt.Print(string(b))

Or dump it after parsing:

r.ParseForm()
fmt.Printf("%#v", r.Form)

I hope this should help you understand where the problem is.

Upvotes: 1

Related Questions