1. 程式人生 > >如何呼叫有道翻譯API(Java,HTTP)

如何呼叫有道翻譯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"}]}