views:

29

answers:

2

Hi,

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

+1  A: 

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 S
A: 

Found the answer at following link:

http://stackoverflow.com/questions/724043/http-url-address-encoding-in-java/724764#724764

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