1

I have my original python script as follows.

#!/usr/bin/env python

import math,sys
import json
import urllib

def gsearch(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  return data

args = sys.argv[1:]
m = 45000000000
if len(args) != 2:
        print "need two words as arguments"
        exit
n0 = int(gsearch(args[0])['cursor']['estimatedResultCount'])
n1 = int(gsearch(args[1])['cursor']['estimatedResultCount'])
n2 = int(gsearch(args[0]+" "+args[1])['cursor']['estimatedResultCount'])

I am in the midst of converting it into java. I have done all the following. I am stuck here search_results = search_response.read() results = json.loads(search_results) data = results['responseData'] . I dont know how to convert these 3 lines into java.

import java.io.*;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLConnection;

public class gi {

   public static void main (String[] args) {

     if(args.length==2){

         for(int i = 0; i < args.length; i++) {
                System.out.println("I IS : "+i+":"+args[i]);
            }
         int n0 = searchGoogle(args[0]);
         int n1 = searchGoogle(args[1]);
         int n2 = searchGoogle(args[0]+" "+args[1]);
     }
     else{
        System.out.println("Not enough arguement");
     }
   }
   public static int searchGoogle(String searchQuery)
   {
    try{

    String query=URLEncoder.encode(searchQuery, "UTF-8");
    String url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s" + query;
    URLConnection connection = new URL(url).openConnection();
    }
    catch(Exception e){
    }
    int pageQty=0;
    return pageQty;
   }

}  // end of ReadString class
3
  • Can you try using jython to run your python code instead of converting it into java? Commented Feb 17, 2014 at 16:48
  • I never come accross jyhton? The problem I need to feed this later into other java application that is the reason I am converting and stuck at these 3 lines Commented Feb 17, 2014 at 16:50
  • If you want to run python code from a java environment for interoperability with java you can use jython. See en.wikipedia.org/wiki/Jython. Commented Feb 17, 2014 at 16:52

1 Answer 1

1

You should be able to make this work using something like the following (this is from this stack overflow answer).

String a = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s";
url = new URL(a);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

Once you have the BufferedReader from the URLConnection, you can get a String object from it:

StringBuilder builder = new StringBuilder();
String aux = "";

while ((aux = reader.readLine()) != null) {
    builder.append(aux);
}

String text = builder.toString();

Once you have the String object, you can pass that into your JSONObject constructor. (from this stack overflow answer).

Using org.json library:

JSONObject jsonObj = new JSONObject(text);

Now that you have your JSONObject, you can use the available methods to extract the data that you need.

Ex:

JSONObject cursorObj = jsonObj.getJSONObject("cursor");
int resultCount = cursorObj.getInt("resultCount");
Sign up to request clarification or add additional context in comments.

8 Comments

I added this URLConnection connection1 = new URL(url).openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(connection1.getInputStream())); but what should I sent into the JSONOBJECt ?
Ok I can get the results ready and my only challenge left now is to look for "cursor":{"resultCount":"58,800,000"," and finally get the resultCount value.
I've updated the answer to include a way to get a string from the BufferedReader from the URLConnection. You may have to format the string before passing it into the JSONObject constructor.
Yes I have followed your way and managed to get the text and the content in text partly is this "cursor":{"resultCount":"58,800,000"," and my final target it to extract the numeric value of resultCount
For an example on extracting data from your JSON object, check our this answer: stackoverflow.com/questions/15918861/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.