import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
public class TestUriForMeMory {
/**
*
* @param 从内存中读取
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String sb=jsonload("word");
System.out.println(sb);
}
public static String jsonload(String word) throws MalformedURLException, IOException, UnsupportedEncodingException {
String wz="http://fanyi.youdao.com/openapi.do?"
+ "keyfrom=TellToMe&key=1289928476&"
+ "type=data&doctype=json&version=1.1&q="
+ word;
//返回内容
StringBuffer sbuffer=new StringBuffer();
//创建地址链接
URL url=new URL(wz);
//打开网络链接
URLConnection urlconn=url.openConnection();
//获取网络链接资源流
InputStream input= urlconn.getInputStream();
//将获取的网页内容转换为utf-8模式
InputStreamReader inreader=new InputStreamReader(input,"utf-8");
//将读取内容写入到内存 从内存中读取!
char[] ch=new char[1024];
StringBuffer sb=new StringBuffer();
int result;
while((result=inreader.read(ch))!=-1){
String st=new String(ch,0,result);
sb.append(st);
}
//将输出结果给String
String jieguo= JosnParser(sb.toString());
sbuffer.append(jieguo);
//关闭流
inreader.close();
input.close();
return sbuffer.toString();
}
static String JosnParser(String path) throws JsonIOException, JsonSyntaxException, FileNotFoundException{
//返回值
StringBuffer sb=new StringBuffer();
//创建json解析器
JsonParser jp=new JsonParser();
//获取解析文件路径
JsonObject obj=(JsonObject) jp.parse(path);
//将解析结果打印
JsonArray st=obj.get("translation").getAsJsonArray();
for(int i=0;i<st.size();i++)
{
String result=st.get(i).getAsString();
sb.append(result+"\n");
}
System.out.println("详细解析");
//获取对象内子对象数组内的元素
JsonObject jso= obj.get("basic").getAsJsonObject();
JsonArray array= jso.get("explains").getAsJsonArray();
for(int i=0;i<array.size();i++)
{
String result=array.get(i).getAsString();
sb.append(result+"\n");
}
return sb.toString();
}
}
====================================
eclipse JFrame button 中的关键代码!
ok_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text= input_tv.getText();
//判断textview是否为空!
if(text!=null&&!text.equals("")){
//URLEncoder.encode("你好","utf-8")
//如果是中文
if(text.matches("^[\u4e00-\u9fa5]{0,}$")){
try {
//翻译
String result= TestUriForMeMory.jsonload(URLEncoder.encode(text,"utf-8"));
result_Pl.setText(result);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
try {
String result= TestUriForMeMory.jsonload(text);
result_Pl.setText(result);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});