如何提取结果Google Custom search?

时间:2017-10-25 15:47:42

标签: android json search google-search android-json

我正在使用以下两项功能进行Google自定义搜索:

Thread thread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {

                try {

                    // looking for
                    String strNoSpaces = str.replace(" ", "+");

                    // Your API key
                    String key="AIzaSyBewkknFVuG68bIjao5sg98kYuPmZuNLvs";

                    // Your Search Engine ID
                    String cx = "013787635589838199944:m7q-rztdo1w";

                    String url2 = "https://www.googleapis.com/customsearch/v1?q=" + strNoSpaces + "&key=" + key + "&cx=" + cx + "&alt=json";
                    Log.d("search", "Url = "+  url2);
               String result2 = httpGet(url2);


                    result.setText(result2);

                }
                catch(Exception e) {
                    System.out.println("Error1 " + e.getMessage());
                }

            }
public String httpGet(String urlStr) throws IOException, JSONException {

    URL url = new URL(urlStr);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        if(conn.getResponseCode() != 200) {

            throw new IOException(conn.getResponseMessage());
        }

        Log.d("search", "Connection status = " + conn.getResponseMessage());

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;

        while((line = rd.readLine()) != null) {

            Log.d("search", "Line =" + rd.readLine());
            sb.append(line+"\n");
        }
        rd.close();

        conn.disconnect();
        return sb.toString();
    }

这是我在TextView中看到的结果,搜索例如“karaoke”:

Searching "karaoke"

我想在TextView中只看到每个视频的标题和链接。在这种情况下,“唱王卡拉OK”和下一个搜索。

1 个答案:

答案 0 :(得分:0)

您收到的答案是json - 已格式化。 将其解析为数据结构(例如使用Gson)并提取您感兴趣的部分。