3

I used to use DefaultHttpClient for my networking code, but decided to change to HttpURLConnection.

I have searched for other questions on how to send POST messages (eg How to add parameters to HttpURLConnection using POST), but for some reason my Flask app always gives me error 400.

When I use logcat, it indeed displays that my POST message is "username=asdf&password=asdf". I include the code below. Also, if I initialized the cookieManager in the method that called this method (makeServiceCall), will returning cookieManager keep my session for subsequent calls to makeServiceCall?

public CookieManager makeServiceCall(CookieManager cookieManager, String urlString, int method, List<NameValuePair> db) {
    String charset = "UTF-8";
    try {
        URL url = new URL(urlString);

        if (method == POST) {
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            if (db != null) {
                try {
                    urlConnection.setDoInput(true);
                    urlConnection.setDoOutput(true);
                    urlConnection.setChunkedStreamingMode(0);
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setRequestProperty("Accept-Charset", charset);
                    urlConnection.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded");

                    OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(out, charset));
                    Log.d("log", "> " + getQuery(db));
                    writer.write(getQuery(db));
                    writer.flush();
                    writer.close();
                    out.close();

                    //Get Response
                    InputStream in = urlConnection.getInputStream();
                    BufferedReader rd = new BufferedReader(new InputStreamReader(in));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while((line = rd.readLine()) != null) {
                        response.append(line);
                        response.append('\r');
                    }
                    rd.close();
                    Log.d("Read attempt: ", "> " + response.toString());
                }
                finally {
                        urlConnection.disconnect();
                }
            }
        }

etc.

Flask code:

def login():
  error = None
  if request.method == 'POST':
    if request.form['username'] != app.config['USERNAME']:
      error = 'Invalid username'
    elif request.form['password'] != app.config['PASSWORD']:
      error = 'Invalid password'
    else:
      session['logged_in'] = True
      flash('You were logged in')
      return redirect(url_for('show_entries'))
  return render_template('login.html', error=error)
Community
  • 1
  • 1
grapefruit
  • 51
  • 2
  • Where's the decorator on `login`? – Makoto Apr 27 '15 at 06:25
  • `my Flask app always gives me error 400.`. App? An app? I see no 400 in your flask code. So what do you mean? Where comes this 400 from? – greenapps Apr 27 '15 at 08:07
  • `writer.write(getQuery(db));`. We cannot see what gets written there. Wich text is produced by `getQuery(db)` ? You could better temporally or for your stackoverflow conversation put the used text in it. – greenapps Apr 27 '15 at 08:11
  • 1
    `response.append('\r');`. That should be response.append('\n'); or response.append('\r\n');. – greenapps Apr 27 '15 at 08:13
  • Remove the setChunkedStreamingMode line. – greenapps Apr 27 '15 at 08:14
  • 2
    "Remove the setChunkedStreamingMode line." This worked! But I don't understand why. Please explain, thank! BTW error 400 as in HTTP bad request. getQuery will output a string such as "username=asdf&password=asdf". The decorator was there when I pasted it, but it got removed somehow. – grapefruit Apr 27 '15 at 13:16

0 Answers0