我正在尝试使用Flask将数据从Android设备发送到Web服务器。
我只是通过返回一些字符串进行测试。
如果我用IP_Address/playlists
向POSTMAN发送到{"spotify_token":"test token"}
的发布请求,我会得到正确的响应。 {"result":"received token"}
但是如果我尝试使用OkHTTP在Android上发送类似的HTTP Post请求,则会收到错误405。192.168.0.105 - - [19/Jul/2018 17:23:37] "POST //playlists HTTP/1.1" 405 -
来自服务器的响应:
Allow: HEAD, GET, OPTIONS
Content-Length: 178
Server: Werkzeug/0.14.1 Python/3.7.0
Date: Fri, 20 Jul 2018 01:57:56 GMT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
我检查了我的代码,并给出了其他答案,据我所知它看起来是正确的。此外,我还可以在主页上执行GET请求。
Android代码
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public void onClick(View view){
client = new OkHttpClient();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("UserId", "test token");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url(IP_ADDRESS + "/playlists")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("ExportButton", e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("ExportButton", response.body().string());
if(response.isSuccessful()){
final String myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
messageWindow.setText(myResponse);
}
});
}
}
});
烧瓶代码
@app.route('/playlists', methods =["POST"])
def get_playlists():
data = request.get_json()
spotify_token = data['spotify_token']
print(spotify_token)
return jsonify({'result': 'received token'})
答案 0 :(得分:0)
我打印出响应,发现要访问的完整URL是“ http://IP_Address//playlists”(有两个“ /”,这就是为什么它得到错误的原因。
感谢Mushtu。