1. 程式人生 > >運用有道api介面寫一個小翻譯(簡單版)

運用有道api介面寫一個小翻譯(簡單版)

package com.zhidi.zuoye;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;


import org.json.JSONException;
import org.json.JSONObject;


//設計一個翻譯程式,
//使用者在控制檯輸入一個英文單詞,
//返回相關的翻譯內容(使用json,面向物件)
public class Zuoye {
public static void main(String[] args) throws IOException, JSONException {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入英文單詞:");
String str=sc.nextLine();
Zuoye.get(str);
}
public static void get(String code) throws IOException, JSONException{
String s=Zuoye.zxc("http://fanyi.youdao.com/openapi.do?keyfrom=youdanfanyi123&key=1357452033&type=data&doctype=json&version=1.1&q="+code);
System.out.println(s);
JSONObject obj = new JSONObject(s);
}
public static String zxc(String uri) throws IOException{
URL url = new URL(uri);
InputStream is = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String str;
StringBuilder sb = new StringBuilder();
while ((str = br.readLine()) != null) {
sb.append(str);
}
br.close();
is.close();
return sb.toString();



}


}