Java / Flask POST请求

时间:2016-02-14 12:45:03

标签: java android python rest flask

我正在尝试从我的Android应用程序向运行一些Flask代码的服务器发送一些数据。我正在使用HTTPUrlConnection向Flask服务器发出POST请求。我已经能够使用Flask创建REST API,但我不确定为什么我的Java到Python通信不起作用。我从服务器收到以下错误"POST /signUp HTTP/1.1" 400 -,我无法解决这个错误(在Flask中打开调试)。我应该如何将JSON数据传递到我的服务器?我的Flask代码应该如何解释这个?

我的Java代码是:

        URL url = new URL(url);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        OutputStream stream = connection.getOutputStream();
        writer = new DataOutputStream(stream);

        Log.d("WARN", getQuery(params)); 
        // The LogCat prints out data like: 
        // ID:test,Email:test@gmail.com,Pwd:test

        writer.writeBytes(getQuery(params));
        writer.flush();
        writer.close();
        stream.close();

// getQuery function aims to create a JSON string to send to the Flask server.
private String getQuery(List<Pair<String, String>> params)
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (Pair<String, String> pair : params)
    {
        if (first)
            first = false;
        else
            result.append(",");

        result.append(pair.first);
        result.append(":");
        result.append(pair.second);
    }

    return result.toString();
}

我的服务器端代码是:

@app.route("/signUp", methods=['POST'])
def signUp():
  req_json = request.get_json()
  g.cursor.execute("INSERT INTO test (ID, Email, Pwd) VALUES (%s,%s,%s)", (req_json['ID'], req_json['Email'], req_json['Pwd']))
  g.conn.commit()
  resp = Response("Updated", status=201, mimetype='application/json')
  return resp

1 个答案:

答案 0 :(得分:0)

// The LogCat prints out data like: 
// ID:test,Email:test@gmail.com,Pwd:test

这不是JSON字符串,因此在服务器端烧瓶将无法反序列化它。你JSON应该是这样的:

// {"ID":"test","Email":"test@gmail.com","Pwd":"test"}

顺便说一下,您可以使用一些更高级别的流畅API来生成JSON,而不是在生成JSON字符串时处理低级别的字符串连接,例如jackson或org.json API