【问题标题】:Getting 301 while doing HTTP get call using Java but getting 200 while doing same using Postman使用 Java 进行 HTTP 获取调用时获取 301,但使用 Postman 执行相同操作时获取 200
【发布时间】:2021-05-22 01:03:46
【问题描述】:

我正在使用 Java 对给定 URL 执行 GET 请求。我收到 301 错误。但是当我使用邮递员执行相同的 GET req 时,我得到了 200。我无法弄清楚出了什么问题。 这是我的 Java 代码-

public static void main(String args[]) throws IOException {
    URL url = new URL("http://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict/?district_id=637&date=22-05-2021");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "PostmanRuntime/7.26.10");
    con.setRequestProperty("Accept-Language", "en_US");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "application/json");
    BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }
    in.close();
}

让我知道这是否可以解决。

谢谢 阿喜

【问题讨论】:

  • 当您通过浏览器提取该 URL 时会得到什么?
  • 我得到成功和相应的输出
  • 你可以在code下从Postman获取你的请求的CURL命令,比较curl的内容和java中的内容
  • 我从 http 更改为 https 并且它正在工作。

标签: java api http postman


【解决方案1】:

如果您收到 301 Moved HTTP 状态代码,则表明服务器上发生了重定向,并且 HttpURLConnection 仅在使用相同协议时才应该遵循重定向。因此,您应该尝试将 URL 协议从 http:// 更改为 https://

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    相关资源
    最近更新 更多