2017-02-24 36 views
0

我想了解如何連接到一個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; 
    } 
} 

}

回答

0

你寫的代碼看起來從我的URL獲取HTML/JSON響應數據重定向沒有被處理,而且很天真。您可以通過檢查值爲200的hcon.getResponseCode()來處理代碼中的重定向,以便您成功讀取數據。如果它不是200以及其他類似301(重定向)或403(需要授權),則需要相應處理這些響應。

在這裏,我給你一個簡單的代碼,它使用來自Apache的HttpClient(我使用httpclient-4.2.1)庫,並以String返回響應。

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 

import org.apache.commons.fileupload.util.Streams; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

public class HttpUtils { 
    private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class); 

    public static String getResponse(String url) throws IOException { 
     return getResponse(url, "UTF-8"); 
    } 

    public static String getResponse(String url, String characterEncoding) throws IOException { 
     return getByteArrayOutputStream(url).toString(characterEncoding); 
    } 

    public static byte[] getBytes(String url) throws IOException { 
     return getByteArrayOutputStream(url).toByteArray(); 
    } 

    public static ByteArrayOutputStream getByteArrayOutputStream(String url) throws IOException { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 

     HttpResponse response = httpclient.execute(httpGet); 
     LOGGER.debug("Status Line: " + response.getStatusLine()); 
     HttpEntity resEntity = response.getEntity(); 

     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
     Streams.copy(resEntity.getContent(), byteArrayOutputStream, true); 
     return byteArrayOutputStream; 
    } 

    public static void main(String[] args) throws IOException { 
     System.out.println(getResponse("https://www.reddit.com/r/AskReddit/.json")); 
    } 

} 

使用此代碼來實現你想要什麼,如果你不希望使用API​​的HTTPClient,然後修改現有的代碼來處理HTTP狀態代碼,但它會是簡單的供你使用上面的代碼。

相關問題