开发者

Google Language detection api replying error code 406

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.getIn开发者_StackOverflow社区putStream()));
        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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜