From 1556423ff3026af6d891750b5186c4686978ea8a Mon Sep 17 00:00:00 2001 From: getpro Date: Thu, 21 Mar 2019 10:38:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + META-INF/MANIFEST.MF | 3 + i02Translate.iml | 13 + i02Translate.properties | 4 + i02Translate.xml | 263 ++++++++++++++++++ module_irskjtranslate.xml | 97 +++++++ .../IrskjTranslate/META-INF/plugin.xml | 39 +++ .../i02Translate/META-INF/plugin.xml | 44 +++ resources/META-INF/plugin.xml | 44 +++ src/win/i02/Demo.java | 8 + src/win/i02/StringToUnicodeAction.java | 81 ++++++ src/win/i02/TranslateAction.java | 132 +++++++++ src/win/i02/bean/TranslationBean.java | 222 +++++++++++++++ src/win/i02/bean/TranslationGoogleBean.java | 244 ++++++++++++++++ src/win/i02/util/HttpUtils.java | 217 +++++++++++++++ src/win/i02/util/StreamUtils.java | 28 ++ src/win/i02/util/TranslateCallBack.java | 36 +++ 17 files changed, 1476 insertions(+) create mode 100644 META-INF/MANIFEST.MF create mode 100644 i02Translate.iml create mode 100644 i02Translate.properties create mode 100644 i02Translate.xml create mode 100644 module_irskjtranslate.xml create mode 100644 out/production/IrskjTranslate/META-INF/plugin.xml create mode 100644 out/production/i02Translate/META-INF/plugin.xml create mode 100644 resources/META-INF/plugin.xml create mode 100644 src/win/i02/Demo.java create mode 100644 src/win/i02/StringToUnicodeAction.java create mode 100644 src/win/i02/TranslateAction.java create mode 100644 src/win/i02/bean/TranslationBean.java create mode 100644 src/win/i02/bean/TranslationGoogleBean.java create mode 100644 src/win/i02/util/HttpUtils.java create mode 100644 src/win/i02/util/StreamUtils.java create mode 100644 src/win/i02/util/TranslateCallBack.java diff --git a/.gitignore b/.gitignore index a1c2a23..ee31d72 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* +/.idea diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF new file mode 100644 index 0000000..838f8da --- /dev/null +++ b/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: win.i02.util.Test + diff --git a/i02Translate.iml b/i02Translate.iml new file mode 100644 index 0000000..e025b20 --- /dev/null +++ b/i02Translate.iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/i02Translate.properties b/i02Translate.properties new file mode 100644 index 0000000..679bde9 --- /dev/null +++ b/i02Translate.properties @@ -0,0 +1,4 @@ +path.variable.kotlin_bundled=C\:\\Program Files\\JetBrains\\IntelliJ IDEA 2017.1.3\\plugins\\Kotlin\\kotlinc +path.variable.maven_repository=C\:\\Users\\Qi\\.m2\\repository +jdk.home.intellij_idea_iu-171.4424.56=C\:/Program Files/JetBrains/IntelliJ IDEA 2017.1.3 +javac2.instrumentation.includeJavaRuntime=false \ No newline at end of file diff --git a/i02Translate.xml b/i02Translate.xml new file mode 100644 index 0000000..4585637 --- /dev/null +++ b/i02Translate.xml @@ -0,0 +1,263 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/module_irskjtranslate.xml b/module_irskjtranslate.xml new file mode 100644 index 0000000..7396929 --- /dev/null +++ b/module_irskjtranslate.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/out/production/IrskjTranslate/META-INF/plugin.xml b/out/production/IrskjTranslate/META-INF/plugin.xml new file mode 100644 index 0000000..ab05e6a --- /dev/null +++ b/out/production/IrskjTranslate/META-INF/plugin.xml @@ -0,0 +1,39 @@ + + win.i02.plugin + 谷歌翻译 + 1.0 + 赵宇麒 + + + 主要针对注释翻译,去除注释的*号,和html标签
+ 使用google api翻译 + ]]>
+ + + most HTML tags may be used + ]]> + + + + + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/out/production/i02Translate/META-INF/plugin.xml b/out/production/i02Translate/META-INF/plugin.xml new file mode 100644 index 0000000..e2111d8 --- /dev/null +++ b/out/production/i02Translate/META-INF/plugin.xml @@ -0,0 +1,44 @@ + + win.i02.plugin + TranslateByGoogle + 1.0 + 赵宇麒 + + https://github.com/PingerOne/A8Translate 的翻译插件
+ 主要针对注释翻译,去除注释的*号,和html标签
+ 使用google api翻译
+ 热键alt+e + 2、字符串Unicode编码,热键shift+q + ]]>
+ + + + + + + + + + com.intellij.modules.lang + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/resources/META-INF/plugin.xml b/resources/META-INF/plugin.xml new file mode 100644 index 0000000..e2111d8 --- /dev/null +++ b/resources/META-INF/plugin.xml @@ -0,0 +1,44 @@ + + win.i02.plugin + TranslateByGoogle + 1.0 + 赵宇麒 + + https://github.com/PingerOne/A8Translate 的翻译插件
+ 主要针对注释翻译,去除注释的*号,和html标签
+ 使用google api翻译
+ 热键alt+e + 2、字符串Unicode编码,热键shift+q + ]]>
+ + + + + + + + + + com.intellij.modules.lang + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/src/win/i02/Demo.java b/src/win/i02/Demo.java new file mode 100644 index 0000000..bb53831 --- /dev/null +++ b/src/win/i02/Demo.java @@ -0,0 +1,8 @@ +package win.i02; + +/** + * 对对对 + * Created by irskj on 2018/9/27. + */ +public class Demo { +} diff --git a/src/win/i02/StringToUnicodeAction.java b/src/win/i02/StringToUnicodeAction.java new file mode 100644 index 0000000..9bf4b41 --- /dev/null +++ b/src/win/i02/StringToUnicodeAction.java @@ -0,0 +1,81 @@ +package win.i02; + +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.PlatformDataKeys; +import com.intellij.openapi.command.WriteCommandAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.SelectionModel; +import org.apache.http.util.TextUtils; + +/** + * Created by irskj on 2018/9/27. + */ +public class StringToUnicodeAction extends AnAction { + private Editor mEditor; + private long latestClickTime; // 上一次的点击时间 + + @Override + public void actionPerformed(AnActionEvent e) { + if (!isFastClick(1000)) { + stringToUnicode(e); + } + } + + public void stringToUnicode(AnActionEvent e) { + /** + * 第一步 --> 选中单词 + */ + // 获取动作编辑器 + mEditor = e.getData(PlatformDataKeys.EDITOR); + if (mEditor == null) { + return; + } + + // 获取选择模式对象 + SelectionModel model = mEditor.getSelectionModel(); + + if (model.getSelectedText() == null) { + return; + } + + // 选中文字 + String selectedText = model.getSelectedText(); + if (TextUtils.isEmpty(selectedText)) { + return; + } + WriteCommandAction.runWriteCommandAction(e.getProject(), new Runnable() { + @Override + public void run() { + String content = mEditor.getDocument().getText(); + String start = content.substring(0,model.getSelectionStart()); + String end = content.substring(model.getSelectionEnd()); + mEditor.getDocument().setText(start+ChinaToUnicode(selectedText)+end); + } + }); + } + + /* * from Chinese to Unicode */ + public static String ChinaToUnicode(String str) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < str.length(); i++) { + int chr = str.charAt(i); + result.append("\\u").append(Integer.toHexString(chr)); + } + return result.toString(); + } + + + /** + * 屏蔽多次选中 + */ + public boolean isFastClick(long timeMillis) { + long time = System.currentTimeMillis(); + long timeD = time - latestClickTime; + if (0 < timeD && timeD < timeMillis) { + return true; + } + latestClickTime = time; + return false; + } +} diff --git a/src/win/i02/TranslateAction.java b/src/win/i02/TranslateAction.java new file mode 100644 index 0000000..177f4f9 --- /dev/null +++ b/src/win/i02/TranslateAction.java @@ -0,0 +1,132 @@ +package win.i02; + +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.PlatformDataKeys; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.SelectionModel; +import com.intellij.openapi.ui.popup.Balloon; +import com.intellij.openapi.ui.popup.JBPopupFactory; +import com.intellij.ui.JBColor; +import org.apache.http.util.TextUtils; +import win.i02.bean.TranslationGoogleBean; +import win.i02.util.HttpUtils; +import win.i02.util.TranslateCallBack; + +import java.awt.*; + +/** + * Created by irskj on 2017/11/20. + */ +public class TranslateAction extends AnAction{ + private Editor mEditor; + private long latestClickTime; // 上一次的点击时间 + + @Override + public void actionPerformed(AnActionEvent e) { + + if (!isFastClick(1000)) { + performTranslation(e); + } + } + + /** 执行翻译 */ + private void performTranslation(AnActionEvent e) { + + /** + * 第一步 --> 选中单词 + */ + // 获取动作编辑器 + mEditor = e.getData(PlatformDataKeys.EDITOR); + if (mEditor == null) { + return; + } + + // 获取选择模式对象 + SelectionModel model = mEditor.getSelectionModel(); + + if(model.getSelectedText()==null) { + return; + } + + // 选中文字 + String selectedText = model.getSelectedText().replaceAll("\\*",""); + selectedText = selectedText.replaceAll("<(\\\\|/)*[a-zA-Z]+>",""); + if (TextUtils.isEmpty(selectedText)) { + return; + } + + HttpUtils.requestGoogle(selectedText, new TranslateCallBack() { + @Override + public void onSuccess(TranslationGoogleBean result) { + if(TextUtils.isEmpty(result.getCode())){ + showPopupWindow(result.toString()); + }else{ + showPopupWindow(result.getCode()); + } + + } + + @Override + public void onFailure(String message) { + showPopupWindow(message); + } + + @Override + public void onError(String message) { + showPopupWindow(message); + } + }); + + /** + * 第二步 ---> API查询 + */ +// HttpUtils.requestData(selectedText, new TranslateCallBack() { +// +// @Override +// public void onSuccess(TranslationBean result) { +// showPopupWindow(result.toString()); +// } +// +// @Override +// public void onFailure(String message) { +// showPopupWindow(message); +// } +// +// @Override +// public void onError(String message) { +// showPopupWindow(message); +// } +// }); + + } + + + /** + * 第三步 --> 弹出对话框 + * + * @param result + */ + private void showPopupWindow(final String result) { + ApplicationManager.getApplication().invokeLater(() -> { + JBPopupFactory factory = JBPopupFactory.getInstance(); + factory.createHtmlTextBalloonBuilder(result, null, new JBColor(new Color(186, 238, 186), new Color(73, 117, 73)), null) + .setFadeoutTime(5000) + .createBalloon() + .show(factory.guessBestPopupLocation(mEditor), Balloon.Position.below); + }); + } + + + /** 屏蔽多次选中 */ + public boolean isFastClick(long timeMillis) { + long time = System.currentTimeMillis(); + long timeD = time - latestClickTime; + if (0 < timeD && timeD < timeMillis) { + return true; + } + latestClickTime = time; + return false; + } +} diff --git a/src/win/i02/bean/TranslationBean.java b/src/win/i02/bean/TranslationBean.java new file mode 100644 index 0000000..e1977b6 --- /dev/null +++ b/src/win/i02/bean/TranslationBean.java @@ -0,0 +1,222 @@ +package win.i02.bean; + +import java.util.List; + +/** + * Created by irskj on 2017/11/20. + */ +public class TranslationBean{ + + /** + * 返回错误码的状态,有道返回 + */ + private final static int SUCCESS = 0; // 成功 + private final static int QUERY_STRING_TOO_LONG = 20; // 要翻译的文本过长 + private final static int CAN_NOT_TRANSLATE = 30; // 无法进行有效的翻译 + private final static int INVALID_LANGUAGE = 40; // 不支持的语言类型 + private final static int INVALID_KEY = 50; // 无效的key + private final static int NO_RESULT = 60; // 无词典结果 + public final static String EMPTY = "返回数据为空"; + + /** + * translation : ["解决"] + * basic : {"us-phonetic":"rɪ'zɑlv","phonetic":"rɪ'zɒlv","uk-phonetic":"rɪ'zɒlv","explains":["n. 坚决;决定要做的事","vt. 决定;溶解;使\u2026分解;决心要做\u2026","vi. 解决;决心;分解"]} + * query : resolve + * errorCode : 0 + * web : [{"value":["决心","决定","解决"],"key":"Resolve"},{"value":["归结为","使分解为","分解为"],"key":"resolve into"},{"value":["解决分歧","消除分歧"],"key":"resolve differences"}] + */ + + public BasicBean basic; + public String query; + public int errorCode; + public List translation; + public List web; + + class BasicBean { + public String usPhonetic; + public String phonetic; + public String ukPhonetic; + public List explains; + } + + class WebBean { + public String key; + public List value; + } + + + /** + * 取错误信息 + */ + private String getErrorMessage() { + switch (errorCode) { + case SUCCESS: + return "成功"; + case QUERY_STRING_TOO_LONG: + return "要翻译的文本过长"; + case CAN_NOT_TRANSLATE: + return "无法进行有效的翻译"; + case INVALID_LANGUAGE: + return "不支持的语言类型"; + case INVALID_KEY: + return "无效的key"; + case NO_RESULT: + return "无词典结果"; + default: + return "你选中的是什么鬼?"; + } + } + + + /** + * 获取不同语言的翻译内容 + */ + private String getPhonetic() { + if (basic == null) { + return null; + } + + String phonetic = null; + String us_phonetic = basic.usPhonetic; + String uk_phonetic = basic.ukPhonetic; + if (us_phonetic == null && uk_phonetic == null) { + + phonetic = "发音:[" + basic.phonetic + "];"; + } else { + if (us_phonetic != null) { + phonetic = "美式:[" + us_phonetic + "];"; + } + if (uk_phonetic != null) { + if (phonetic == null) { + phonetic = ""; + } + phonetic = phonetic + "英式:[" + uk_phonetic + "];"; + } + } + System.out.println(phonetic); + return phonetic; + } + + /** + * 获取翻译 + */ + private String getExplains() { + if (basic == null) { + return null; + } + String result = null; + List explains = basic.explains; + if (explains.size() > 0) { + result = ""; + } + for (String explain : explains) { + result += explain + "\n"; + } + return result; + } + + /** + * 获取直接的翻译结果 + */ + private String getTranslationResult() { + if (translation == null) { + return null; + } + String result = null; + if (translation.size() > 0) { + result = ""; + } + + for (int i = 0; i < translation.size(); i++) { + String keyword = translation.get(i); + if (i < translation.size() - 1) { + result += (keyword + ","); + } else { + result += (keyword + ";"); + } + } + return result; + } + + /** + * 获取网络翻译结果 + */ + private String getWebResult() { + if (web == null) { + return null; + } + String result = null; + if (web.size() > 0) { + result = ""; + } + + for (WebBean webBean : web) { + String key = webBean.key; + result += (key + ":"); + + List value = webBean.value; + for (int i = 0; i < value.size(); i++) { + String keyword = value.get(i); + if (i < value.size() - 1) { + result += (keyword + ","); + } else { + result += keyword; + } + } + + result += "\n"; + } + + return result; + } + + private boolean isSentence() { + return query==null||query.trim().contains(" "); + } + + /** + * 结果 + */ + @Override + public String toString() { + String string = null; + if (errorCode != SUCCESS) { + string = "错误代码:" + errorCode + "\n" + getErrorMessage(); + } else { + String translation = getTranslationResult(); + if (translation != null) { + translation = translation.substring(0, translation.length() - 1); + if (!translation.equals(query)) { + if (isSentence()) { + string = getTranslationResult() + "\n"; + } else { + string = (query + ":" + getTranslationResult() + "\n"); + } + } + } + if (getPhonetic() != null) { + if (string == null) { + string = ""; + } + string += (getPhonetic() + "\n"); + } + if (getExplains() != null) { + if (string == null) { + string = ""; + } + string += (getExplains()); + } + if (getWebResult() != null) { + if (string == null) { + string = ""; + } + string += "网络释义:\n"; + string += (getWebResult()); + } + } + if (string == null) { + string = "你选的内容:" + query + "\n抱歉,翻译不了..."; + } + return string; + } +} diff --git a/src/win/i02/bean/TranslationGoogleBean.java b/src/win/i02/bean/TranslationGoogleBean.java new file mode 100644 index 0000000..51fcd46 --- /dev/null +++ b/src/win/i02/bean/TranslationGoogleBean.java @@ -0,0 +1,244 @@ +package win.i02.bean; + +/** + * + * @author irskj + * @date 2017/11/21 + */ +public class TranslationGoogleBean{ + /** + * raw : + * from : {"language":{"didYouMean":false,"iso":"en"},"text":{"didYouMean":true,"autoCorrected":false,"value":"Classes that can be used to bootstrap and launch a Spring application from a Java main method."}} + * text : 可用于从Java主方法引导和启动Spring应用程序的类。默认情况下,类将执行以下步骤来引导您的应用程序 + */ + private String raw; + private FromEntity from; + private String text; + private String code; + + @Override + public String toString() { + if(text==null){ + return "请求失败"; + } + return text; + } + + public void setRaw(String raw) { + this.raw = raw; + } + + public void setFrom(FromEntity from) { + this.from = from; + } + + public void setText(String text) { + this.text = text; + } + + public String getRaw() { + return raw; + } + + public FromEntity getFrom() { + return from; + } + + public String getText() { + return text; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public class FromEntity { + /** + * language : {"didYouMean":false,"iso":"en"} + * text : {"didYouMean":true,"autoCorrected":false,"value":"Classes that can be used to bootstrap and launch a Spring application from a Java main method."} + */ + private LanguageEntity language; + private TextEntity text; + + public void setLanguage(LanguageEntity language) { + this.language = language; + } + + public void setText(TextEntity text) { + this.text = text; + } + + public LanguageEntity getLanguage() { + return language; + } + + public TextEntity getText() { + return text; + } + + public class LanguageEntity { + /** + * didYouMean : false + * iso : en + */ + private boolean didYouMean; + private String iso; + + public void setDidYouMean(boolean didYouMean) { + this.didYouMean = didYouMean; + } + + public void setIso(String iso) { + this.iso = iso; + } + + public boolean isDidYouMean() { + return didYouMean; + } + + public String getIso() { + return iso; + } + } + + public class TextEntity { + /** + * didYouMean : true + * autoCorrected : false + * value : Classes that can be used to bootstrap and launch a Spring application from a Java main method. + */ + private boolean didYouMean; + private boolean autoCorrected; + private String value; + + public void setDidYouMean(boolean didYouMean) { + this.didYouMean = didYouMean; + } + + public void setAutoCorrected(boolean autoCorrected) { + this.autoCorrected = autoCorrected; + } + + public void setValue(String value) { + this.value = value; + } + + public boolean isDidYouMean() { + return didYouMean; + } + + public boolean isAutoCorrected() { + return autoCorrected; + } + + public String getValue() { + return value; + } + } + } +// String text; +// String raw; +// From from; +// +// public String getText() { +// return text; +// } +// +// public void setText(String text) { +// this.text = text; +// } +// +// public String getRaw() { +// return raw; +// } +// +// public void setRaw(String raw) { +// this.raw = raw; +// } +// +// public From getFrom() { +// return from; +// } +// +// public void setFrom(From from) { +// this.from = from; +// } +// +// public static class From { +// Language language; +// Text text; +// +// public Language getLanguage() { +// return language; +// } +// +// public void setLanguage(Language language) { +// this.language = language; +// } +// +// public Text getText() { +// return text; +// } +// +// public void setText(Text text) { +// this.text = text; +// } +// } +// +// public static class Language { +// boolean didYouMean; +// String iso; +// +// public boolean isDidYouMean() { +// return didYouMean; +// } +// +// public void setDidYouMean(boolean didYouMean) { +// this.didYouMean = didYouMean; +// } +// +// public String getIso() { +// return iso; +// } +// +// public void setIso(String iso) { +// this.iso = iso; +// } +// } +// +// public static class Text { +// boolean autoCorrected; +// boolean didYouMean; +// String value; +// +// public boolean isAutoCorrected() { +// return autoCorrected; +// } +// +// public void setAutoCorrected(boolean autoCorrected) { +// this.autoCorrected = autoCorrected; +// } +// +// public boolean isDidYouMean() { +// return didYouMean; +// } +// +// public void setDidYouMean(boolean didYouMean) { +// this.didYouMean = didYouMean; +// } +// +// public String getValue() { +// return value; +// } +// +// public void setValue(String value) { +// this.value = value; +// } +// } + + +} diff --git a/src/win/i02/util/HttpUtils.java b/src/win/i02/util/HttpUtils.java new file mode 100644 index 0000000..6d24a52 --- /dev/null +++ b/src/win/i02/util/HttpUtils.java @@ -0,0 +1,217 @@ +package win.i02.util; + +import com.google.gson.Gson; +import org.apache.http.HttpEntity; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +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 org.apache.http.util.EntityUtils; +import win.i02.bean.TranslationBean; +import win.i02.bean.TranslationGoogleBean; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.*; + +/** + * Created by irskj on 2017/11/20. + */ +public class HttpUtils { + // private static final String BASE_URL = "http://fanyi.youdao.com/openapi.do?keyfrom=Skykai521&key=977124034&type=data&doctype=json&version=1.1&q="; + public static final String appKey = "2b80d4bbd8eaa871"; + public static final String appSec = "IPUSCS4lWbvM3nCdcKkXwV3sKBAFDfMU"; + private static final String BASE_URL = "http://openapi.youdao.com/api?from=EN&to=zh-CHS"; + +// private static final String BASE_GOOGLE_URL="https://translate.google.com/translate_a/single?client=t&sl=en&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=btn&ssel=3&tsel=0&kc=0&tk=955354.586851&q="; + + +// public static void requestNetDataGoogle(String q,TranslateCallBack callBack){ +// try { +// URL url = new URL(BASE_URL + q); +// HttpURLConnection conn = (HttpURLConnection) url.openConnection(); +// +// conn.setConnectTimeout(5000); +// conn.setReadTimeout(5000); +// conn.setRequestMethod(conn.getRequestMethod()); +// +// // 连接成功 +// if (conn.getResponseCode() == 200) { +// InputStream ins = conn.getInputStream(); +// +// // 获取到Json字符串 +// String content = StreamUtils.getStringFromStream(ins); +// if (content != null) { +// callBack.onSuccess(new Gson().fromJson(content, callBack.mType)); +// } else { +// callBack.onFailure(TranslationBean.EMPTY); +// } +// } else { +// callBack.onFailure(conn.getResponseMessage()); +// } +// } catch (java.io.IOException e) { +// e.printStackTrace(); +// callBack.onFailure(e.getMessage()); +// } +// } + + public static String genarator(String q) { + int slat = new Random().nextInt(); + String sign = md5(appKey + q + slat + appSec); + return "&appKey=" + appKey + "&salt=" + slat + "&sign=" + sign + "&q"; + } + + /** + * 生成32位MD5摘要 + * + * @param string + * @return + */ + public static String md5(String string) { + if (string == null) { + return null; + } + char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F'}; + + try { + byte[] btInput = string.getBytes("utf-8"); + /** 获得MD5摘要算法的 MessageDigest 对象 */ + MessageDigest mdInst = MessageDigest.getInstance("MD5"); + /** 使用指定的字节更新摘要 */ + mdInst.update(btInput); + /** 获得密文 */ + byte[] md = mdInst.digest(); + /** 把密文转换成十六进制的字符串形式 */ + int j = md.length; + char str[] = new char[j * 2]; + int k = 0; + for (byte byte0 : md) { + str[k++] = hexDigits[byte0 >>> 4 & 0xf]; + str[k++] = hexDigits[byte0 & 0xf]; + } + return new String(str); + } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { + return null; + } + } + + /** + * 请求网络数据 + */ + public static void requestNetData(String queryWord, TranslateCallBack callBack) { + // TODO 读取本地缓存 + + String urlString = BASE_URL + genarator(queryWord); + + try { + URL url = new URL(urlString + queryWord); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setConnectTimeout(5000); + conn.setReadTimeout(5000); + conn.setRequestMethod(conn.getRequestMethod()); + + // 连接成功 + if (conn.getResponseCode() == 200) { + InputStream ins = conn.getInputStream(); + + // 获取到Json字符串 + String content = StreamUtils.getStringFromStream(ins); + System.out.println("返回值:" + content); + if (content != null) { + callBack.onSuccess(new Gson().fromJson(content, callBack.mType)); + } else { + callBack.onFailure(TranslationBean.EMPTY); + } + } else { + callBack.onFailure(conn.getResponseMessage()); + } + } catch (java.io.IOException e) { + e.printStackTrace(); + callBack.onFailure(e.getMessage()); + } + } + + public static void requestData(String q, TranslateCallBack callBack) { + String salt = String.valueOf(System.currentTimeMillis()); + String from = "EN"; + String to = "zh-CHS"; + String sign = md5(appKey + q + salt + appSec); + Map params = new HashMap(); + params.put("q", q); + params.put("from", from); + params.put("to", to); + params.put("sign", sign); + params.put("salt", salt); + params.put("appKey", appKey); + try { + String result = requestForHttp("http://openapi.youdao.com/api", params); + if (result == null) { + callBack.onFailure("请求失败"); + } else { + callBack.onSuccess(new Gson().fromJson(result, callBack.mType)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void requestGoogle(String q, TranslateCallBack callBack) { + Map params = new HashMap<>(); + params.put("q", q); + try { + String result = requestForHttp("http://qr.i02.win/translate", params); + if (result != null) { + callBack.onSuccess(new Gson().fromJson(result, callBack.mType)); + } else { + callBack.onFailure("请求失败"); + } + } catch (Exception e) { + e.printStackTrace(); + callBack.onFailure(e.getMessage()); + } + } + + public static String requestForHttp(String url, Map requestParams) throws Exception { + String result = null; + CloseableHttpClient httpClient = HttpClients.createDefault(); + /**HttpPost*/ + HttpPost httpPost = new HttpPost(url); + List params = new ArrayList(); + Iterator> it = requestParams.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry en = it.next(); + String key = en.getKey(); + String value = en.getValue(); + if (value != null) { + params.add(new BasicNameValuePair(key, value)); + } + } + httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + /**HttpResponse*/ + CloseableHttpResponse httpResponse = httpClient.execute(httpPost); + try { + HttpEntity httpEntity = httpResponse.getEntity(); + result = EntityUtils.toString(httpEntity, "utf-8"); + EntityUtils.consume(httpEntity); + } finally { + try { + if (httpResponse != null) { + httpResponse.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + +} diff --git a/src/win/i02/util/StreamUtils.java b/src/win/i02/util/StreamUtils.java new file mode 100644 index 0000000..63c5413 --- /dev/null +++ b/src/win/i02/util/StreamUtils.java @@ -0,0 +1,28 @@ +package win.i02.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by irskj on 2017/11/20. + */ +public class StreamUtils { + /** + * 将输入流转换成字符串 + * @param ins + * @return + */ + public static String getStringFromStream(InputStream ins) throws IOException { + // 内层流读取数据 + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + int len = 0; + byte[] buffer = new byte[1024]; + // 写入数据到输出流 + while ((len = ins.read(buffer)) != -1) { + outputStream.write(buffer, 0, len); + } + // 返回字符串 + return new String(outputStream.toByteArray(),"UTF-8"); + } +} diff --git a/src/win/i02/util/TranslateCallBack.java b/src/win/i02/util/TranslateCallBack.java new file mode 100644 index 0000000..84701dd --- /dev/null +++ b/src/win/i02/util/TranslateCallBack.java @@ -0,0 +1,36 @@ +package win.i02.util; + +import com.google.gson.internal.$Gson$Types; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +/** + * Created by irskj on 2017/11/20. + */ +public abstract class TranslateCallBack { + public Type mType; + + public TranslateCallBack() { + mType = getSuperclassTypeParameter(getClass()); + } + + /** 数据类型 */ + static Type getSuperclassTypeParameter(Class subclass) { + Type superclass = subclass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("Missing mType parameter."); + } + ParameterizedType parameterizedType = (ParameterizedType) superclass; + return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]); + } + + /** 请求成功 */ + public abstract void onSuccess(T result); + + /** 请求失败 */ + public abstract void onFailure(String message); + + /** 请求发生错误 */ + public abstract void onError(String message); +}