HttpURLConnection getInputStream()未读取任何内容



下面是在Android应用程序中使用Reddit API的示例。我使用的是安卓工作室和Java。我有一个链接,它在GET请求时返回一个JSON对象(比如http://www.reddit.com/r/dragonforce/.json),教程中有这样一段代码:

public static HttpURLConnection getConnection(String url){
System.out.println("URL: "+url);
HttpURLConnection hcon = null;
try {
hcon=(HttpURLConnection) new URL(url).openConnection();
hcon.setReadTimeout(30000); // Timeout at 30 seconds
hcon.setRequestProperty("User-Agent", "Alien V1.0");
} catch (MalformedURLException e) {
Log.e("getConnection()",
"Invalid URL: "+e.toString());
} catch (IOException e) {
Log.e("getConnection()",
"Could not connect: "+e.toString());
}
return hcon;
}

public static String readContents(String url){
HttpURLConnection hcon=getConnection(url);
if(hcon==null) return null;
try{
StringBuffer sb=new StringBuffer(8192);
String tmp="";
BufferedReader br=new BufferedReader(
new InputStreamReader(
hcon.getInputStream()
)
);
tmp = br.readLine();
while(tmp !=null) {
sb.append(tmp).append("n");
tmp = br.readLine();
}
br.close();
return sb.toString();
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}

出于调试目的,我分离了tmp分配。问题是没有从inputStream中读取任何内容,并且它向JSONObject解析器返回一个空缓冲区,从而导致JSONException end of input at character 0 of。我在Manifest for INTERNET中拥有用户权限,从URL读取的语法似乎得到了互联网上其他来源的支持,但似乎仍然有问题。如有任何帮助,我们将不胜感激。

对于任何正在阅读本文的人来说,问题是教程中的URL使用了HTTP而不是HTTPS,导致重定向响应代码,并且没有返回任何内容。

相关内容

最新更新