【问题标题】:How to fix urlConnection.getResponseCode = 403如何修复 urlConnection.getResponseCode = 403
【发布时间】:2015-07-20 14:11:15
【问题描述】:

这是我的代码:

urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();    
                    int status = urlConnection.getResponseCode();
                    // Read the input stream into a String
                    InputStream inputStream = urlConnection.getInputStream();
                    StringBuffer buffer = new StringBuffer();
                    if (inputStream == null) {
                        return;
                    }
                    reader = new BufferedReader(new InputStreamReader(inputStream));

这是我的 JSON 示例:

[{"Id":1,"Name":"Алупка","RegionId":1},{"Id":2,"Name":"Алушта","RegionId":1},{"Id":3,"Name":"Армянськ","RegionId":1}]

这里是网址:http://donor.ua/api/cities?sign=9u1AARsgKybup3vz9CaQnw==ivbCaKmrWpgz

但是urlConnection.getResponseCode() 仍然返回“403”。

请告诉我如何解决这个问题! 提前致谢!

【问题讨论】:

  • 您是否尝试将 URL 更改为 https?服务器告诉我它是必需的,当我更改它时,我得到了有效负载。

标签: android json http-status-code-403 urlconnection http-response-codes


【解决方案1】:

当我尝试加载您在问题中提供的 URL 时,它说需要 HTTPS。使用 Firebug,我确认在这种情况下服务器实际上返回了 403。将协议从 http 更改为 https 会按预期返回 JSON。因此,在您的代码中,当您创建 URL 对象时,请确保您指定的 URL 以 https:// 而不是 http://

开头

【讨论】:

    【解决方案2】:

    错误可能是由于服务器拒绝连接,因为您没有发送“User-Agent”。

    添加此行以修复它:

    connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 2020-05-24
      • 2021-11-11
      • 2018-05-21
      • 2023-01-20
      相关资源
      最近更新 更多