Skip to content

Commit 54d5920

Browse files
authored
Merge pull request #122 from Alice-175/master
HTTP请求无HTTP前缀时默认添加http://前缀
2 parents 026b738 + 6c17385 commit 54d5920

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

src/main/java/com/luoboduner/moo/tool/service/HttpMsgSender.java

+3
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,9 @@ public HttpSendResult sendUseOkHttp() {
172172
if (httpMsg.getCookies() != null && !httpMsg.getCookies().isEmpty()) {
173173
requestBuilder.addHeader(Header.COOKIE.toString(), cookieHeader(httpMsg.getCookies()));
174174
}
175+
if(!httpMsg.getUrl().toLowerCase().startsWith("http")&&!httpMsg.getUrl().toLowerCase().startsWith("https")){
176+
httpMsg.setUrl("http://" + httpMsg.getUrl());
177+
}
175178
switch (HttpMsgMaker.method) {
176179
case "GET":
177180
HttpUrl.Builder urlBuilder = HttpUrl.parse(httpMsg.getUrl()).newBuilder();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.luoboduner.moo.tool.util;
2+
3+
import cn.hutool.json.JSONArray;
4+
import org.apache.commons.lang3.StringUtils;
5+
6+
import java.io.BufferedReader;
7+
import java.io.InputStreamReader;
8+
import java.net.HttpURLConnection;
9+
import java.net.URL;
10+
import java.net.URLEncoder;
11+
import java.nio.charset.StandardCharsets;
12+
13+
/**
14+
* 翻译工具类
15+
*/
16+
public class GoogleTranslatorUtil {
17+
18+
/**
19+
*
20+
* @param word
21+
* @param sourceLanguage 源语言 默认auto 英文为 en
22+
* @param targetLanguage 目标语言 默认zh-CN
23+
* @return
24+
*/
25+
public static String translate(String word,String sourceLanguage,String targetLanguage){
26+
try {
27+
if(StringUtils.isEmpty(sourceLanguage)){
28+
sourceLanguage="auto";
29+
}
30+
if(StringUtils.isEmpty(targetLanguage)){
31+
targetLanguage="zh-CN";
32+
}
33+
String url = "https://translate.googleapis.com/translate_a/single?" +
34+
"client=gtx&" +
35+
"sl=" + sourceLanguage +
36+
"&tl=" + targetLanguage +
37+
"&dt=t&q=" + URLEncoder.encode(word, StandardCharsets.UTF_8);
38+
39+
URL obj = new URL(url);
40+
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
41+
con.setRequestProperty("User-Agent", "Mozilla/5.0");
42+
43+
BufferedReader in = new BufferedReader(
44+
new InputStreamReader(con.getInputStream()));
45+
String inputLine;
46+
StringBuilder response = new StringBuilder();
47+
48+
while ((inputLine = in.readLine()) != null) {
49+
response.append(inputLine);
50+
}
51+
in.close();
52+
return parseResult(response.toString());
53+
}catch (Exception e){
54+
return word;
55+
}
56+
}
57+
58+
private static String parseResult(String inputJson){
59+
JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0);
60+
StringBuilder result = new StringBuilder();
61+
for (Object o : jsonArray2) {
62+
result.append(((JSONArray) o).get(0).toString());
63+
}
64+
return result.toString();
65+
}
66+
}

0 commit comments

Comments
 (0)