如何调用有道翻译API(Java,HTTP)

申请Key

首先如图进入有道翻译,在下方点击“有道翻译API”。

技术分享

紧接着来调用数据接口,按提示完成下列输入框。

技术分享

如下图所示,已经申请成功了。

技术分享

下图是官方给的示例,可以有xml和json、jsonp等三种数据格式。

技术分享

代码(Java)

public class TestPost {

    public static void main(String[] args) {
        new ReadByPost().start();
    }

}

class ReadByPost extends Thread{
    @Override
    public void run() { 
        try {


            URL url = new URL("http://fanyi.youdao.com/openapi.do");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.addRequestProperty("encoding", "UTF-8");
            connection.setDoInput(true);
            connection.setDoOutput(true);

            connection.setRequestMethod("POST");

            OutputStream os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);


            bw.write("keyfrom=fadabvaa&key=522071532&type=data&doctype=json&version=1.1&q=Microsoft");
            bw.flush();

            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,"UTF-8");
            BufferedReader br = new BufferedReader(isr);

            String line;
            StringBuilder builder = new StringBuilder();
            while((line = br.readLine()) != null){
                builder.append(line);
            }

            bw.close();
            osw.close();
            os.close();

            br.close();
            isr.close();
            is.close();

            System.out.println(builder.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出如下:

{"translation":["微软"],"basic":{"us-phonetic":"‘maikr?us?ft","phonetic":"‘maikr?us?ft","uk-phonetic":"‘maikr?us?ft","explains":["n. 微软公司(全球知名的PC软件主要厂商)"]},"query":"Microsoft","errorCode":0,"web":[{"value":["微软公司","微软","美国微软"],"key":"MicroSoft"},{"value":["办公软件","微软办公软件","微软办公"],"key":"Microsoft Office"},{"value":["微软小工具"],"key":"Microsoft Gadgets"}]}

版权声明:本文为 NoMasp柯于旺 原创文章,未经许可严禁转载!欢迎访问我的博客:http://blog.csdn.net/nomasp

文章来自:http://blog.csdn.net/nomasp/article/details/48995039
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3