我想了解如何連接到一個API和receieve和解析JSON數據,所以我目前正在跟蹤該網頁上的一個例子:http://www.whycouch.com/2012/12/how-to-create-android-client-for-reddit.html,但我得到一個錯誤,指出:爲什麼我的Android應用程序連接到Reddit API,但獲得空白的響應?
E/fetchPosts(): org.json.JSONException: End of input at character 0 of
我的應用程序因爲它說新的主機連接已經建立,所以我不太確定它爲什麼會得到空白的響應。以下是我的課程,獲取連接並讀取內容。如果我不得不猜測我錯了什麼地方,我會說它與請求屬性有關,但我去reddit的網站並按照他們想要的格式化它,它仍然沒有返回任何東西。謝謝。
public class RemoteData {
/*
This method returns a connection to the specified URL,
with necessary properties like timeout and user-agent
set to your requirements.
*/
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 set at 30 seconds
hcon.setRequestProperty("User-Agent", "android:com.example.reddittestappbydrew:v0.0.1");
}catch(MalformedURLException e){
Log.e("getConnection()", "Invalid URL: " +e.toString());
}catch (IOException e){
Log.e("getConnection()", "Could not connect: " + e.toString());
}
return hcon;
}
/*
A utility method that reads the contents of a url and returns them as a string
*/
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()));
while((tmp = br.readLine()) != null){
sb.append(tmp).append("\n");
}
br.close();
return sb.toString();
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}
}