2013-04-09 113 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

回答