简体   繁体   中英

How to extract results Google Custom search?

I'm doing a Google Custom Search with this 2 functions:

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();
    }

And this is the result that I see in the TextView, searching for example "karaoke":

搜索“卡拉OK”

I want is to see in the TextView only the Title and Link of each video. In this case "Sing King Karaoke" and the next ones of the search.

The answer you're receiving is json -formatted. Parse it into a datastructure (eg using Gson) and extract the part you're interested in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM