JSON file not getting downloaded, function returns null

后端 未结 3 1801
刺人心
刺人心 2021-01-24 08:34

I am trying to download some JSON from the google book API.

The URL and API-Key I\'m using seems to work becuase i can fetch it manually with a browser. I call this cl

3条回答
  •  离开以前
    2021-01-24 09:28

    Ok, after some informative input and research I've found a connection method that connects to the google book api and retrieves the JSON. The connection does use the TrustEveryOne class but it does retrieve the JSON. I'll have to work on certificate auth later, app isnt distributed yet.

    public static JSONObject getJSONfromURL(String urlpass) throws ParseException, IOException{
    
        /*//initialize*/
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;
        int response = -1;
    
        URL url = new URL(urlpass);
        TrustEveryone.trustEveryone();
        URLConnection conn = url.openConnection();
    
        if (!(conn instanceof HttpURLConnection))                     
            throw new IOException("Not an HTTP connection");        
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                is = httpConn.getInputStream();                                 
            }                     
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");            
        }
    
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }
        /*//try parse the string to a JSON object*/
        try{
            jArray = new JSONObject(result);
        }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
        }
    
        return jArray;    
    }
    

提交回复
热议问题