- import java.util.List;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.NameValuePair;
- import org.apache.commons.httpclient.methods.GetMethod;
- import com.google.gson.Gson;
- public class Baidu {
- private static String url = "http://openapi.baidu.com/public/2.0/bmt/translate";
- private static String api_key = "****************";
- public static void main(String[] args) throws Exception {
- HttpClient client = new HttpClient();
- GetMethod method = new GetMethod(url);
- method.setQueryString(new NameValuePair[] {
- new NameValuePair("from", "zh"),
- new NameValuePair("to", "en"),
- new NameValuePair("client_id", api_key),
- // 多条内容用\\n分隔
- new NameValuePair("q", "【微语】任何一件无缝的天衣,都需要你一针一线认真缝合。\\n海天盛宴大野模,土包子眼中的白富美。") });
- client.executeMethod(method);
- String response = new String(method.getResponseBodyAsString());
- System.out.println(response);
- method.releaseConnection();
- Gson gson = new Gson();
- BaiduTrans bt = gson.fromJson(response, BaiduTrans.class);
- for (TransResult tr : bt.getTrans_result()) {
- System.out.println(tr.getDst());
- }
- }
- class BaiduTrans {
- private String from;
- private String to;
- private List<TransResult> trans_result;
- public String getFrom() {
- return from;
- }
- public void setFrom(String from) {
- this.from = from;
- }
- public String getTo() {
- return to;
- }
- public void setTo(String to) {
- this.to = to;
- }
- public List<TransResult> getTrans_result() {
- return trans_result;
- }
- public void setTrans_result(List<TransResult> trans_result) {
- this.trans_result = trans_result;
- }
- }
- class TransResult {
- public String getSrc() {
- return src;
- }
- public void setSrc(String src) {
- this.src = src;
- }
- public String getDst() {
- return dst;
- }
- public void setDst(String dst) {
- this.dst = dst;
- }
- private String src;
- private String dst;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0912201411195.html
来源: http://www.codesnippet.cn/detail/0912201411195.html