在Android中使用Google Books API [英] Using Google Books API in Android

查看:106
本文介绍了在Android中使用Google Books API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是Android新手,使用网络API。我目前正在编写一个应用程序,可以扫描书籍中的条形码,然后在Google Books中搜索它。

到目前为止,我已经将Scandit应用到了我的应用程序中,并且已经从Books API的Google API控制台注册并获得了API密钥。从那里我不知道如何继续并开始编码。到目前为止,从我的理解来看,它要求我通过uri发出请求数据,但是我坚持如何实际对其进行编码。我想知道是否有人可以指点我正确的方向或提供一个示例代码,显示如何使用URI获取数据。



我还下载了压缩Book API Jar库

a>我需要利用这个吗?我问这个问题是因为从本网站的Google Places API上的一个问题,其中一个答案表示,您所需要的只是使用Google API作为构建目标,并且不需要任何Jar文件,但这是否适用于Books API好吧?

另外我使用Eclipse,我应该将我的构建目标设置为Google API 16吗?我猜这是正确的,因为我计划今后使用Google地图。



感谢这是我第一次在这里问一个问题。

解决方案

我刚刚完成了这个工作。这就是我使用 HttpURLConnection AsyncTask 实现它的原因(我只是打电话给 https://www.googleapis.com/books/v1/volumes?q=isbn :+ yourISBN并解析JSON):

  //从Barcode Scanner接收到的ISBN。发送到GoogleBooks以获取图书信息。 
class GoogleApiRequest扩展AsyncTask< String,Object,JSONObject> {

@Override
保护无效onPreExecute(){
//检查网络连接。
if(isNetworkConnected()== false){
//取消请求。
Log.i(getClass()。getName(),未连接到互联网);
取消(true);
return;

$ b @Override
protected JSONObject doInBackground(String ... isbns){
// Stop if cancel
if(isCancelled()) {
返回null;
}

字符串apiUrlString =https://www.googleapis.com/books/v1/volumes?q=isbn:+ isbns [0];
尝试{
HttpURLConnection连接= null;
//建立连接。
尝试{
URL url = new URL(apiUrlString);
connection =(HttpURLConnection)url.openConnection();
connection.setRequestMethod(GET);
connection.setReadTimeout(5000); // 5秒
connection.setConnectTimeout(5000); // 5秒
} catch(MalformedURLException e){
//不可能:应用中使用的唯一两个URL取自字符串资源。
e.printStackTrace();
} catch(ProtocolException e){
//不可能:GET是一个完全有效的请求方法。
e.printStackTrace();
}
int responseCode = connection.getResponseCode();
if(responseCode!= 200){
Log.w(getClass()。getName(),GoogleBooksAPI request request failed。Response Code:+ responseCode);
connection.disconnect();
返回null;
}

//从响应中读取数据。
StringBuilder builder = new StringBuilder();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = responseReader.readLine();
while(line!= null){
builder.append(line);
line = responseReader.readLine();
}
String responseString = builder.toString();
Log.d(getClass()。getName(),Response String:+ responseString);
JSONObject responseJson = new JSONObject(responseString);
//关闭连接并返回响应代码。
connection.disconnect();
return responseJson;
} catch(SocketTimeoutException e){
Log.w(getClass()。getName(),Connection timed out。Returning null);
返回null;
} catch(IOException e){
Log.d(getClass()。getName(),连接到Google Books API时发生IOException);
e.printStackTrace();
返回null;
} catch(JSONException e){
Log.d(getClass()。getName(),连接到Google Books API时发生JSONException);
e.printStackTrace();
返回null;

$ b @Override
protected void onPostExecute(JSONObject responseJson){
if(isCancelled()){
// Request is cancelled due to无网络连接。
showNetworkDialog();
} else if(responseJson == null){
showSimpleDialog(getResources()。getString(R.string.dialog_null_response));
}
其他{
//一切顺利。用新的JSONObject做些什么。



$ b protected boolean isNetworkConnected(){

//必要时实例化mConnectivityManager
if(mConnectivityManager == null){
mConnectivityManager =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
}
//设备是否连接到互联网?
NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
if(networkInfo!= null&& amp; networkInfo.isConnected()){
return true;
} else {
return false;
}
}

我将对话方法的代码省略为他们不相关。希望这有助于。


Hi I'm new to Android and using web APIs. I'm currently writing an application that can scan a barcode from a book and then search Google Books for it.

So far I implemented Scandit into my application and I registered and got the API key from Google API console for Books API. From there I do not know how to continue and start coding it. So far from my understanding it requires me make a request data via uri but I'm stuck on how to actually code it. I'm wondering if anyone could point me to the right direction or provide a sample code that shows how to fetch data using URI.

I also downloaded the zipped Book API Jar libraries do I need to make use of this? I ask this because from a question on Google Places API on this website, one of the answer said that all you need is to use Google API as the build target and it doesn't require any Jar files but does this apply to Books API as well?

Also I'm using Eclipse, should I set my build target to be Google APIs 16? I'm guessing this is right since I plan to use Google Maps in future with this app.

Thanks this is first time I asked a question on here.

解决方案

I just finished doing this myself. This is how I implemented it using an HttpURLConnection and an AsyncTask (I just call "https://www.googleapis.com/books/v1/volumes?q=isbn:"+yourISBN and parse the JSON):

// Received ISBN from Barcode Scanner. Send to GoogleBooks to obtain book information.
class GoogleApiRequest extends AsyncTask<String, Object, JSONObject>{

    @Override
    protected void onPreExecute() {
        // Check network connection.
        if(isNetworkConnected() == false){
            // Cancel request.
            Log.i(getClass().getName(), "Not connected to the internet");
            cancel(true);
            return;
        }
    }
    @Override
    protected JSONObject doInBackground(String... isbns) {
        // Stop if cancelled
        if(isCancelled()){
            return null;
        }

        String apiUrlString = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbns[0];
        try{
            HttpURLConnection connection = null;
            // Build Connection.
            try{
                URL url = new URL(apiUrlString);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(5000); // 5 seconds
                connection.setConnectTimeout(5000); // 5 seconds
            } catch (MalformedURLException e) {
                // Impossible: The only two URLs used in the app are taken from string resources.
                e.printStackTrace();
            } catch (ProtocolException e) {
                // Impossible: "GET" is a perfectly valid request method.
                e.printStackTrace();
            }
            int responseCode = connection.getResponseCode();
            if(responseCode != 200){
                Log.w(getClass().getName(), "GoogleBooksAPI request failed. Response Code: " + responseCode);
                connection.disconnect();
                return null;
            }

            // Read data from response.
            StringBuilder builder = new StringBuilder();
            BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = responseReader.readLine();
            while (line != null){
                builder.append(line);
                line = responseReader.readLine();
            }
            String responseString = builder.toString();
            Log.d(getClass().getName(), "Response String: " + responseString);
            JSONObject responseJson = new JSONObject(responseString);
            // Close connection and return response code.
            connection.disconnect();
            return responseJson;
        } catch (SocketTimeoutException e) {
            Log.w(getClass().getName(), "Connection timed out. Returning null");
            return null;
        } catch(IOException e){
            Log.d(getClass().getName(), "IOException when connecting to Google Books API.");
            e.printStackTrace();
            return null;
        } catch (JSONException e) {
            Log.d(getClass().getName(), "JSONException when connecting to Google Books API.");
            e.printStackTrace();
            return null;
        }
    }
    @Override
    protected void onPostExecute(JSONObject responseJson) {
        if(isCancelled()){
            // Request was cancelled due to no network connection.
            showNetworkDialog();
        } else if(responseJson == null){
            showSimpleDialog(getResources().getString(R.string.dialog_null_response));
        }
        else{
            // All went well. Do something with your new JSONObject.
        }
    }
}

protected boolean isNetworkConnected(){

    // Instantiate mConnectivityManager if necessary
    if(mConnectivityManager == null){
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    }
    // Is device connected to the Internet?
    NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
    if(networkInfo != null && networkInfo.isConnected()){
        return true;
    } else {
        return false;
    }
}

I've omitted the code for my dialog methods as they are not relevant. Hope this helps.

这篇关于在Android中使用Google Books API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆