source: DRBLTranslatorHelper/src/com/google/api/translate/Translate.java @ 19

Last change on this file since 19 was 14, checked in by sunny, 17 years ago
File size: 2.2 KB
RevLine 
[14]1/**
2 * Translate.java
3 *
4 * Makes the Google Translate API available to Java applications.
5 */
6package com.google.api.translate;
7
8import java.io.BufferedReader;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.InputStreamReader;
12import java.net.HttpURLConnection;
13import java.net.MalformedURLException;
14import java.net.URL;
15import java.net.URLEncoder;
16
17/**
18 * @author rich
19 * Makes the Google Translate API available to Java applications.
20 */
21public class Translate {
22 
23  private static final String ENCODING = "UTF-8";
24    private static final String URL_STRING = "http://translate.google.com/translate_t?langpair=";
25    private static final String TEXT_VAR = "&text=";
26
27    /**
28     * @param text The String to translate.
29     * @param from The language code to translate from.
30     * @param to The language code to translate to.
31     * @return The translated String.
32     * @throws MalformedURLException
33     * @throws IOException
34     */
35    public static String translate(String text, String from, String to) throws MalformedURLException, IOException {
36        StringBuilder url = new StringBuilder();
37        url.append(URL_STRING).append(from).append('|').append(to);
38        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));
39
40        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
41        uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
42
43        String page = toString(uc.getInputStream());
44       
45        int resultBox = page.indexOf("<div id=result_box dir=");
46       
47        if (resultBox < 0) throw new Error("No translation result returned.");
48
49        String start = page.substring(resultBox);
50        return start.substring(27, start.indexOf("</div>"));
51    }
52
53    private static String toString(InputStream inputStream) throws IOException {
54        String string;
55        StringBuilder outputBuilder = new StringBuilder();
56        if (inputStream != null) {
57            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING));
58            while (null != (string = reader.readLine())) {
59                outputBuilder.append(string).append('\n');
60            }
61        }
62        return outputBuilder.toString();
63    }
64}
Note: See TracBrowser for help on using the repository browser.