Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get JSON response to HTTP query in android

Tags:

json

android

I am trying to get bing results to my query in JSON form and then make its JSON object and perform somethings on it.

But I am not able to receive the response :(

I tried following two approaches.

Can anybody help me in resolving problem?

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

As you can see, I tried with both using API key and without using API key. But still problem at line commented as problem is here.

Approach 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();  
              }  
like image 587
adityag Avatar asked Jan 30 '26 13:01

adityag


1 Answers

And that's why we suggest you always include a logcat output since there's no way we could have figured it out without it.

Add this to your AndroidManifest.xml:

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

You're getting a SecurityException because you haven't told Android that you're using the network.

like image 66
Brian Dupuis Avatar answered Feb 01 '26 05:02

Brian Dupuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!