【问题标题】:How do I use GET method with sending json data in android?如何使用 GET 方法在 android 中发送 json 数据?
【发布时间】: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 请求。

Python Interpreter

无法解决这个问题吗?

【问题讨论】:

  • 是否可以使用 HttpUrlConnection 来做到这一点?
  • 如果我仍然无法解释,我很抱歉。

标签: java android android-studio


【解决方案1】:

Request Body 不建议在 HTTP GET 请求中使用。见HERE

GET 请求消息中的有效负载没有定义的语义; 在 GET 请求上发送有效负载正文可能会导致一些现有的 拒绝请求的实现。

当您尝试在 URL 上写入时,尽管您已将 GET 设置为 HTTP 方法,但您隐式地在其上写入 POST。在下面几行:

OutputStream os = connection.getOutputStream();
byte[] input = jsonInput.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);

要确认我的话,请参阅Writing to a URLConnection

写入 URL 通常称为发布到 URL。服务器 识别 POST 请求并读取客户端发送的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2013-07-10
    • 2019-06-24
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多