java调用百度api_java httpclient调用百度api接口实现翻译测试

该博客展示了如何使用Java的HttpClient库调用百度API进行翻译。通过设置请求参数,从API获取响应,然后解析JSON响应以展示翻译结果。示例中,将中文字符串“初次见面”翻译成了日文。
摘要由CSDN通过智能技术生成

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;

/**

* @author quanmin

*

*/

public class Baidu {

private static String url = " http://openapi.baidu.com/public/2.0/bmt/translate";

private static String api_key = "SK5Xqu91Dd95RocfjaU2ndGn";

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", "jp"),

new NameValuePair("client_id", api_key),

// 多条内容用\n分隔

new NameValuePair("q", "初次见面") });

client.executeMethod(method);

String response = new String(method.getResponseBodyAsString());

System.out.println(Native2AsciiUtils.ascii2Native(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 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 getTrans_result() {

return trans_result;

}

public void setTrans_result(List 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;

}

}

还有一个是Native和Ascii转换

5f44669d9023f819b9cfa4031178418d.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值