这是我的代码:
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”。
请告诉我如何解决这个问题! 提前谢谢!
答案 0 :(得分:1)
当我尝试加载您在问题中提供的URL时,它表示需要HTTPS。使用Firebug,我确认在这种情况下服务器实际上返回403。将协议从http
更改为https
会按预期返回JSON。因此,在您的代码中,当您创建URL
对象时,请确保您指定的URL以https://而不是http://
答案 1 :(得分:-1)
The error could be due to server is rejecting the connection due to you are not sending "User-Agent".
add this line in order to fix it:
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");