java - 从网站获取数据到 Google Glass

标签 java json parsing google-glass

我仍在学习如何从网站中提取数据,我真的希望我能得到一些适合初学者的好答案。无论如何,我的目标是在我的应用程序后台提取数据(无需在我的应用程序中打开并显示它)。这个想法是,数据将被存储以供以后使用。 我使用的 API 有 2 个 GetMethods: GetProductJSON(具有 JSON 响应)和 GetProduct(具有逗号分隔值 (CSV) 响应) 以下是 JSON 响应网站的示例:

     {"0":{"productname":"Neutrogena Lips Stick 4.8g","imageurl":"http://ecx.images-  amazon.com/images/I/31E1ct854gL._SL160_.jpg","producturl":"","price":"5.65","currency":"USD","saleprice":"","storename":"N/A"}}

逗号分隔值响应如下所示:

     "productname","imageurl","producturl","price","currency","saleprice","storename"
     "Neutrogena Lips Stick 4.8g","http://ecx.images-amazon.com/images/I/31E1ct854gL._SL160_.jpg","","5.65","USD","","N/A"

这是我如何称呼该网站:

    url = url.replace("{CODE}", codeValue);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    cardPresenter.setPendingIntent(createPendingIntent(getContext(), intent));

有关如何使其成为后台任务以及如何在 java 中实际获取数据以便我可以在 Livecard 上使用它们的任何建议。

最佳答案

首先,您需要能够访问互联网。将以下权限包含到您的 AndroidManifest.xml 中:

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

使用GDK和AsyncTask:

import android.os.AsyncTask;

public class RetrieveData extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... resource) {
        String data;
        try {
            URL url = new URL(resource[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(connection.getInputStream());
            data = convertStreamToString(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    private String convertStreamToString(InputStream in) {
        Scanner s = new Scanner(in);
        return s.useDelimiter("\\A").hasNext() ? s.next() : "";
    }
}

描述了方法convertStreamToString() there .

在您的服务或 Activity 中:

String retrievedData;
try {
    retrievedData = new RetrieveData().execute("http://www.example.com/GetProductJSON").get();
} catch (Exception e) {
    e.printStackTrace();
}
// Process data

希望有帮助。

关于java - 从网站获取数据到 Google Glass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22863806/

相关文章:

performance - 使用 R 从 json 文件构建数据帧时,merge() 的有效替代方法?

python - 在 python : how to split newlines while ignoring newline inside quotes 中解析字符串

python - 使用lxml etree在Python中将大型xml文件聚合到字典需要太长时间

java - 如何在spring中接收动态生成的输入值作为bean

javascript - 从 JSON 对象的 HTML 中解析 img

java - 为 android 设置 eclipse 时遇到问题

php - 使用 PHP 来自 mysql 数据库的 JSON 响应显示格式不正确

python - 使用 BeautifulSoup 组合文本输出

java - 获取最近 12 小时的条目 SQLite

java - 如何使用ivy在本地解析