2013-04-09 43 views
1

我一直在這個特定的困境停留了一段時間,我已經搜遍了網站,發現了一些幫助,但沒有對我的特定問題。我試圖連接到一個網站從中提取JSON數據。主機是什麼我不知道:未知的主機異常,Apache HttpClient,Java,wunderground [解決]

DefaultHttpClient client = new DefaultHttpClient(); 
HttpHost targetHost = new HttpHost("www.wunderground.com", 80); 
    HttpGet httpGet = new HttpGet(urllink); // urllink is "api.wunderground.com/api/my_key/conditions/forecast/hourly/alerts/q/32256.json" 
    httpGet.setHeader("Accept", "application/json"); 
    httpGet.setHeader("Content-type", "application/json"); 

    HttpResponse response = client.execute(targetHost, httpGet); 

    HttpEntity entity = response.getEntity(); 
    InputStream instream = entity.getContent(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); 

    StringBuilder stringBuilder = new StringBuilder(); 
    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      stringBuilder.append(line + "\n"); 
     } 
    } catch (Exception e) { 
     // print stacktrace 
     return null; 
    } finally { 
     try { 
      instream.close(); 
     } catch (Exception e) { 
      // print stacktrace 
      return null; 
     } 
    } 

    return stringBuilder.toString(); 

主機既可以是www.wunderground.comapi.wunderground.com,但當我嘗試它們中的任我得到Unknown host exception

我發現了錯誤。這是我沒有在Android清單的權限!

+0

你能發送ping請求?也許你本地安裝有問題。 – sk2212 2013-04-09 14:16:30

+0

嗯,這聽起來像它可能是一些東西。我可以訪問該網站的罰款。但ping它返回「超時」indefinitely – Rapitor 2013-04-09 14:22:41

+0

你的代碼適用於我有點補充:你的** urllink **應該以協議開頭:** http://api.wunderground.com/api/Your_Key/features /settings/q/query.format**。另外,我刪除了unnessecary targetHost,並用** client.execute(httpGet)替換了** client.execute(targetHost,httpGet); ** – Alex 2013-04-09 14:42:37

回答