import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.arnx.jsonic.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class MSTranslatorTest {
public static void main(String[] args) {
try {
MSTranslatorTest app = new MSTranslatorTest();
app.translate();
} catch(Throwable ex) {
ex.printStackTrace(System.err);
}
}
private void translate() throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
// Step1 access_tokenを取得
// 取得のためのリクエストを準備
HttpPost httpPost = new HttpPost("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type", "client_credentials"));
// クライアント IDを設定
params.add(new BasicNameValuePair("client_id", "...."));
// 顧客の秘密を設定
params.add(new BasicNameValuePair("client_secret", "...."));
params.add(new BasicNameValuePair("scope", "http://api.microsofttranslator.com"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
// 取得実行
String accessToken;
HttpResponse response1 = client.execute(httpPost);
try {
// 結果はJSONとして返ってくるのでJSONICでaccess_tokenを切り出す
HttpEntity entity = response1.getEntity();
String reponseText = EntityUtils.toString(entity);
Map json = JSON.decode(reponseText, Map.class);
accessToken = (String)json.get("access_token");
} finally {
httpPost.releaseConnection();
}
// Step2 翻訳する
// 翻訳リクエストURLを作成
// ・翻訳元=日本語 (from=ja)
// ・翻訳先=スペイン語 (to=es)
// ・翻訳する文字列 (text)
String text = "こんにちは";
String uri = String.format("http://api.microsofttranslator.com/V2/Http.svc/Translate?from=ja&to=es&text=%s", text);
// access_tokenをヘッダに付与。"Bearer "を前につける。
String authorization = String.format("Bearer %s", accessToken);
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Authorization", authorization);
// 翻訳実行
HttpResponse response2 = client.execute(httpGet);
try {
// 結果はXMLで返ってくる。そのままコンソールに表示。
HttpEntity entity = response2.getEntity();
String reponseText = EntityUtils.toString(entity);
System.out.println(reponseText);
} finally {
httpGet.releaseConnection();
}
}
}
実行するとコンソールに次のような結果が表示される。
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">¡Buenas noches!</string>
関連記事
0 件のコメント:
コメントを投稿