有道词典简易客户端

最近在学python,发现用python来实现爬虫类操作确实比java要简单许多

有一节课是用python实现有道词典客户端的,就想用java实现以下,弄了半天总算弄好了,水平不高

python代码

import urllib.request
import urllib.parse
import json
import time
while True:
    
    url= "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index"


    text = input("请输入需要翻译的内容(输入exit结束):")
    if text == "exit":
        print("程序退出")
        break
    head = {}
    head["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
    data = { }
    data["type"] = "AUTO"
    data["i"] = text
    data["doctype"] = "json"
    data["xmlVersion"] = "1.8"
    data["keyfrom:fanyi"] = "web"
    data["ue"] = "UTF-8"
    data["action"] = "FY_BY_CLICKBUTTON"
    data["typoResult"] = "true"
    data = urllib.parse.urlencode(data).encode("utf-8")


    req = urllib.request.Request(url,data,head)
    response = urllib.request.urlopen(req)


    html = response.read().decode("utf-8")
    target = json.loads(html)


    result = target["translateResult"][0][0]["tgt"]
    print(result)

java代码

package Demo;

 


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;


import javax.swing.*;


import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
public class YDTranslate {
private static final String url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index";
//主界面
private JFrame frame = null;
//输入界面
JPanel inputpanel = null;
JTextField inputtext = null;
JButton tranButton = null;
//显示面板
JScrollPane jspane = null;
JTextArea showarea = null;
//界面初始化
public void init(){
//输入面板的布局
inputpanel = new JPanel();
inputtext = new JTextField(19);
tranButton = new JButton("翻译");
tranButton.addActionListener(new tranListener());
inputpanel.setLayout(new FlowLayout());
inputpanel.add(inputtext);
inputpanel.add(tranButton);
//显示界面
showarea = new JTextArea();
showarea.setLineWrap(true);
jspane = new JScrollPane(showarea);
jspane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//主界面
frame = new JFrame("翻译");
frame.add(BorderLayout.NORTH,inputpanel);
frame.add(BorderLayout.CENTER,jspane);
//显示
frame.setSize(300,400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);


}
//内部类
class tranListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String word = inputtext.getText();
String preword = translate(word);
String overword = decodejson(preword);
showarea.setText(overword);
}
}
private String translate(String sword) {
//翻译过的字符
String oword = null;
//创建一个客户端
CloseableHttpClient httpclient = HttpClients.createDefault();
//设置post方法
HttpPost postmethod = new HttpPost(url);
//设置读取流
InputStream in = null;
/*设置需要上传的参数,通过谷歌浏览器查到
   type:AUTO
i:hellow
doctype:json
xmlVersion:1.8
keyfrom:fanyi.web
ue:UTF-8
action:FY_BY_ENTER
typoResult:true
*/
ArrayList<NameValuePair> FormData = new ArrayList<NameValuePair>();
FormData.add(new BasicNameValuePair("type","AUTO"));
FormData.add(new BasicNameValuePair("i",sword));
FormData.add(new BasicNameValuePair("doctype","json"));
FormData.add(new BasicNameValuePair("xmlVersion","1.8"));
FormData.add(new BasicNameValuePair("keyfrom","fanyi.web"));
FormData.add(new BasicNameValuePair("ue","UTF-8"));
FormData.add(new BasicNameValuePair("action","FY_BY_ENTER"));
FormData.add(new BasicNameValuePair("typoResult","true"));
try {
//将数据封装到请求中
HttpEntity entity = new UrlEncodedFormEntity(FormData,"utf-8");
//设置请求头
postmethod.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
//设置请求体
postmethod.setEntity(entity);
//执行请求,获得相应
HttpResponse response = httpclient.execute(postmethod);
//定义写入流
in = response.getEntity().getContent();
byte bytes[] = new byte[1024];
int count = 0;
while((count = in.read(bytes)) != -1){
oword = new String(bytes,0,count,"UTF-8");
}
System.out.println(oword);
} catch (UnsupportedEncodingException e) {
System.out.println("post请求设置失败");
}catch(IOException el){
el.printStackTrace();
}finally{
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return oword;
}
private String decodejson(String oword){
String word = null;
try{
//{"type":"EN2ZH_CN","errorCode":0,"elapsedTime":0,"translateResult":[[{"src":"i love you","tgt":"我爱你"}]],"smartResult":{"type":1,"entries":["","我爱你。"]}}
//获取json数据的对象
JSONObject object1 = JSONObject.fromObject(oword);
//获取translateResult对应的字符串
String translateresult = object1.getString("translateResult");
//获取smartResult对应的字符串
String smartresult = object1.getString("smartResult");
//将translateResult对应的字符串封装成对象数组
Object[] arrayfirst = JSONArray.fromObject(translateresult).toArray();
//第二层数组
Object[] arraysecound = JSONArray.fromObject(arrayfirst[0].toString()).toArray();
JSONObject preobject = JSONObject.fromObject(arraysecound[0].toString());
String prestr = preobject.getString("src");
String overstr = preobject.getString("tgt");
try {
word = new String((prestr+":"+overstr).getBytes(),"gbk");
} catch (UnsupportedEncodingException e) {
System.out.println("编码转换失败");
}
}catch(net.sf.json.JSONException el){
System.out.println("未找到智慧翻译");
}finally{
return word;
}
}
public static void main(String[] args) throws UnsupportedEncodingException {
new YDTranslate().init();
}

 

 

}

 

不知道为什么在post参数为中文的时候会乱码,明天再找问题吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值