【发布时间】:2021-12-11 13:16:41
【问题描述】:
Python 中的 API 路由(Flask)
@app.route('/secret')
def secret():
if request.get_json(force=True)['key'] == 'secret key':
return jsonify(msg='Hello!')
它正在运行 linux 终端
curl -iX GET -d '{"key":"secret key"}' localhost
Linux 终端输出 this
{"msg":"Hello!"}
它不需要在浏览器中工作。
try{
HttpURLConnection connection = (HttpURLConnection)
new URL("http://<my local ip>/secret").openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
JSONObject jsonInput = new JSONObject();
jsonInput.put("key", "secret key");
OutputStream os = connection.getOutputStream();
byte[] input = jsonInput.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
os.flush();
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
return response.toString();
} catch (IOException | JSONException e) {
Log.e("MainActivity", "Error: " + e.getMessage());
}
虽然在我的代码中将 GET 方法设置为连接请求,但正在向 Python 服务器发送 POST 请求。
无法解决这个问题吗?
【问题讨论】:
-
是否可以使用 HttpUrlConnection 来做到这一点?
-
如果我仍然无法解释,我很抱歉。
标签: java android android-studio