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
hanleyhansen
  • 6,304
  • 8
  • 37
  • 73
user2711681
  • 285
  • 7
  • 16
  • Can you try using jython to run your python code instead of converting it into java? – RaviH Feb 17 '14 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 – user2711681 Feb 17 '14 at 16:50
  • If you want to run python code from a java environment for interoperability with java you can use jython. See http://en.wikipedia.org/wiki/Jython. – RaviH Feb 17 '14 at 16:52

1 Answers1

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");
Community
  • 1
  • 1
skeryl
  • 5,225
  • 4
  • 26
  • 28
  • 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 ? – user2711681 Feb 17 '14 at 16:57
  • 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. – user2711681 Feb 17 '14 at 17:13
  • 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. – skeryl Feb 17 '14 at 17:14
  • 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 – user2711681 Feb 17 '14 at 17:17
  • For an example on extracting data from your JSON object, check our this answer: http://stackoverflow.com/questions/15918861/how-to-get-data-from-json-object – skeryl Feb 17 '14 at 17:30
  • I am a bit stucked here JSONArray data = jsonResult.getJSONArray("responseData"); if(data != null) { String[] cursors = new String[data.length()]; for(int i = 0 ; i < data.length() ; i++) { cursors[i] = data.getString("cursor"); System.out.println("Curros : "+cursors[i]); } } I get this error error: method getString in class JSONArray cannot be applied to given types; cursors[i] = data.getString("cursor"); – user2711681 Feb 17 '14 at 18:06
  • It looks like that method accepts an integer index parameter, not a string. (see http://www.json.org/javadoc/org/json/JSONArray.html#getString(int) ) – skeryl Feb 17 '14 at 19:43
  • Don't forget to mark this as the answer if it answered your question. – skeryl Feb 18 '14 at 15:49