2016-07-15 81 views
-1

我有一個懷疑與網絡服務和Json有關。其實我有一個網址http://api.icndb.com/jokes/random,這與一些笑話網站有關。如何通過url獲取數據android

如果你點擊上面給出的URL,你可以看到json數據。現在我的問題是我試圖做一個應用程序,即在我的活動中,我有一個按鈕和文本視圖。

如果我們點擊按鈕,它應該從上面給出的網站獲取笑話,它應該以文本視圖顯示。每次如果我點擊按鈕,它應該顯示不同的笑話。

你能幫我通過使用上面給定的URL來獲取數據。

+0

沒有ü嘗試的任何代碼?以下所有三個答案均爲 –

+0

是正確的 – iAndroid

回答

-1

我把這裏code.you需要使用AsyncTask。

public static String getJSONFromUrl(String url) { 

    // make HTTP request 
    try { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     HttpResponse httpResponse = httpClient.execute(httpGet); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 

     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     Log.e("Log","Url1="+url); 
     json = sb.toString(); 

    } catch (Exception e) { 
     Log.e(TAG, "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e(TAG, "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return json; 
} 

取出Result後,解析它。

-1

如果你的問題是如何檢索數據,你應該看看這個解決方案: How to get JSON from URL in Javascript?

如果調用相同的URL在同一個會議上,它會緩存結果。

你只需要添加一個虛假的參數到URL來強制不要求求。

例如,您可以將getTime添加到網址。

var d = new Date(); 
var n = d.getTime(); 
var url = "http://api.icndb.com/jokes/random?n=" + n; 

例如: http://api.icndb.com/jokes/random?n=1468578025752 http://api.icndb.com/jokes/random?n=819929720000