0

我正在尝试在 Android 应用程序中实现http://codify.freebaseapps.com/?request=https%3A%2F%2Fwww.googleapis.com%2Ffreebase%2Fv1%2Fsearch%3Fquery%3DBlue%2BBottle&title=Simple%20Search 。我安装了正确的 api 密钥并与 google api 服务匹配,并在 Referenced Libraries 下导入了适当的 jar 文件。

但是,我的代码每次在模拟器上运行时都会抛出找不到类 - 'com.google.api.client.http.javanet.NetHttpTransport' 错误。有什么建议或反馈吗?

4

2 回答 2

0

您必须将库添加到项目中。

  1. 右键项目
  2. 特性
  3. Java 构建路径
  4. 添加外部 JAR

请阅读这篇文章:未找到 Android 和 Google 客户端 API NetHttptransport 类

于 2013-02-08T15:45:08.117 回答
0

当我构建您链接到的 Codify 应用程序时,我没有针对 Android 对其进行测试,因此在 Android 中可能有更简单的方法。

这是使用 Android SDK 中包含的 Apache HttpClient 和 json.org 的另一种方法。

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;

public class FreebaseSearchTask extends AsyncTask<String, Void, JSONObject> {

    protected JSONObject getJsonContentFromEntity(HttpEntity entity)
            throws IllegalStateException, IOException, JSONException {
        InputStream in = entity.getContent();
        StringBuffer out = new StringBuffer();
        int n = 1;
        while (n > 0) {
            byte[] b = new byte[4096];
            n = in.read(b);
            if (n > 0)
                out.append(new String(b, 0, n));
        }
        JSONObject jObject = new JSONObject(out.toString());
        return jObject;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        String query = params[0];       
        JSONObject result = null;
        try {
            HttpGet httpGet = new HttpGet("https://www.googleapis.com/freebase/v1/search?query=" + URLEncoder.encode(query, "utf-8"));

            HttpResponse response = httpClient.execute(httpGet, localContext);
            HttpEntity entity = response.getEntity();
            result = getJsonContentFromEntity(entity);
        } catch (Exception e) {
            Log.e("error", e.getLocalizedMessage());
        }
        return result;
    }

    protected void onPostExecute(JSONObject result) {
        doSomething(result);
    }
}
于 2013-02-09T00:29:45.550 回答