1

I am trying to use Google language detection API, Right now I am using the sample available on Google documentation as follows:

    public static String googleLangDetection(String str) throws IOException, JSONException{        
        String urlStr = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=";
//        String urlStr = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton";
        URL url = new URL(urlStr+str);
        URLConnection connection = url.openConnection();
//        connection.addRequestProperty("Referer","http://www.hpeprint.com");

        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while((line = reader.readLine()) != null) {
         builder.append(line);
        }

        JSONObject json = new JSONObject(builder.toString());

        for (Iterator iterator = json.keys(); iterator.hasNext();) {
            String type = (String) iterator.next();
            System.out.println(type);
        }

        return json.getString("language");
    }

But I am getting http error code '406'.

I am unable to understand what the problem is? As the google search query(commented) below it is working fine.

The resultant language detection url itself is working fine when I run it in firefox or IE but it's failing in my java code.

Is there something I am doing wrong?

Thanks in advance

Ashish

Ashish Sharma
  • 1,124
  • 2
  • 24
  • 49
  • 1
    Try to take a look at the request using debug proxy such as http://www.fiddler2.com/ (run you program with `-Dhttp.proxyhost=localhost -Dhttp.proxyport=8888` when proxy is running). – axtavt Sep 27 '10 at 15:34

2 Answers2

1

As a guess, whatever is being passed in on str has characters that are invalid in a URL, as the error code 406 is Not Acceptable, and looks to be returned when there is a content encoding issue.

After a quick google, it looks like you need to run your str through the java.net.URLEncoder class, then append it to the URL.

Matt Sieker
  • 9,349
  • 2
  • 25
  • 43
0

Found the answer at following link:

HTTP URL Address Encoding in Java

Had to modify the code as follows:

URI uri = new URI("http","ajax.googleapis.com","/ajax/services/language/detect","v=1.0&q="+str,null);       
URL url = uri.toURL();  
Community
  • 1
  • 1
Ashish Sharma
  • 1,124
  • 2
  • 24
  • 49