在android中获取对HTTP查询的JSON响应

时间:2012-02-11 18:55:41

标签: android json

我试图以JSON形式获取bing结果到我的查询,然后创建它的JSON对象并在其上执行某些操作。

但我无法收到回复:(

我尝试了两种方法。

有人可以帮我解决问题吗?

Approach1:

URL searhURL;
//String imageurl = "http://api.bing.net/json.aspx?AppID="+myBingAppID+"&Query="+formattedQuery+"&Sources=images";
String imageurl="http://www.bing.com/images/search?q="+formattedQuery+"&go=&qs=n&form=QBLH&filt=all";

    URL url = new URL(imageurl);
    InputStream is = null;

      URLConnection connection = url.openConnection();
      Log.d(LOGGER, "1.0");
        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream())); //problem is here
        Log.d(LOGGER, "2.0");
        while ((line = reader.readLine()) != null) {
                builder.append(line);
        }
        Log.d(LOGGER, "3.0");

         jSONString = builder.toString();
        //after cutting off the junk, its ok
        Log.d(LOGGER, "String is : "+jSONString);
        JSONObject jSONObject = new JSONObject(jSONString); //whole json object

正如您所看到的,我尝试使用API​​密钥而不使用API​​密钥。但仍有问题在线评论为问题就在这里。

方法2

         String jsonString="";
        try {  
               URL url = new URL(imageurl);  
               Log.d(LOGGER, "1");
               BufferedReader in = new BufferedReader(new InputStreamReader(  
                 url.openStream())); //problem here 
               Log.d(LOGGER, "2");
               String inputLine;  

               while ((inputLine = in.readLine()) != null) {  
                //JSON data get stored as a string  
                jsonString = inputLine;  

               }  
               Log.d(LOGGER, "3");
               in.close();  
               Log.d(LOGGER, "String is : "+jsonString);
}
        catch (IOException e) {  
               e.printStackTrace();  
              }  

1 个答案:

答案 0 :(得分:7)

这就是为什么我们建议你总是包含一个logcat输出,因为如果没有它我们就无法理解它。

将其添加到AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

您收到的是SecurityException,因为您没有告诉Android您正在使用该网络。