サンプル: Google Translate をもちいた機械翻訳
いがぴょんのサンプルを元に書いてみました。
http://homepage2.nifty.com/igat/igapyon/diary/2010/ig100331.html
これならHttpClientを使わなくても、標準APIだけで作れるんじゃないかな?
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; /** * 参考:Java: サンプル: Google Translate をもちいた機械翻訳 * http://homepage2.nifty.com/igat/igapyon/diary/2010/ig100331.html */ public class GoogleTranslate { void test() throws IOException { String line = URLEncoder.encode("これはペンです。", "UTF-8"); String s = "http://translate.google.co.jp/translate_a/t"+ "?client=t"+ "&text="+line+ "&hl=ja"+ "&sl=ja"+ "&tl=en"+ "&pc=0"; System.out.println(s); URL url = new URL(s); InputStream in = null; ByteArrayOutputStream out = null; try { URLConnection conn = url.openConnection(); conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Java) MyLocal Ext."); conn.addRequestProperty("Accept-Language", "en-us"); conn.addRequestProperty("Accept-Charset", "UTF-8"); in = conn.getInputStream(); out = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytes_read; while((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } byte[] bytes = out.toByteArray(); System.out.println(new String(bytes, "UTF-8")); } finally { try { in.close(); out.close(); } catch(Exception e) {} } } public static void main(String[] args) throws IOException { new GoogleTranslate().test(); } }
こんな形で出力されます。
{"sentences":[{"trans":"This is a pen.","orig":"これはペンです。","translit":""}],"src":"ja"}
以下のURLを直接Webブラウザに入力しても同上の結果が得られます。
http://translate.google.co.jp/translate_a/t?client=t&text=%E3%81%93%E3%82%8C%E3%81%AF%E3%83%9A%E3%83%B3%E3%81%A7%E3%81%99%E3%80%82&hl=ja&sl=ja&tl=en&pc=0