Flask没有从Android接收POST

时间:2015-04-27 06:10:26

标签: java android flask

我曾经使用DefaultHttpClient作为我的网络代码,但决定改为HttpURLConnection。

我搜索了有关如何发送POST消息的其他问题(例如How to add parameters to HttpURLConnection using POST),但由于某种原因,我的Flask应用程序总是给我400错误。

当我使用logcat时,它确实显示我的POST消息是“username = asdf& password = asdf”。我包括下面的代码。另外,如果我在调用此方法的方法(makeServiceCall)中初始化cookieManager,那么将返回cookieManager保持我的会话以便后续调用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();
                }
            }
        }

Flask代码:

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)

0 个答案:

没有答案