-
Notifications
You must be signed in to change notification settings - Fork 1
/
TranslateAPI.java
65 lines (51 loc) · 2.14 KB
/
TranslateAPI.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package me.psrcek.translateAPI;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
public class TranslateAPI {
public static final String API_KEY = "Paste your yandex api key here";
private static String request(String URL) throws IOException {
URL url = new URL(URL);
URLConnection urlConn = url.openConnection();
urlConn.addRequestProperty("User-Agent", "Mozilla");
InputStream inStream = urlConn.getInputStream();
String recieved = new BufferedReader(new InputStreamReader(inStream)).readLine();
inStream.close();
return recieved;
}
public static Map<String, String> getLangs() throws IOException {
String langs = request("https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=" + API_KEY + "&ui=en");
langs = langs.substring(langs.indexOf("langs")+7);
langs = langs.substring(0, langs.length()-1);
String[] splitLangs = langs.split(",");
Map<String, String> languages = new HashMap<String, String>();
for (String s : splitLangs) {
String[] s2 = s.split(":");
String key = s2[0].substring(1, s2[0].length()-1);
String value = s2[1].substring(1, s2[1].length()-1);
languages.put(key, value);
}
return languages;
}
public static String translate(String text, String sourceLang, String targetLang) throws IOException {
String response = request("https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + API_KEY + "&text=" + text + "&lang=" + sourceLang + "-" + targetLang);
return response.substring(response.indexOf("text")+8, response.length()-3);
}
public static String detectLanguage(String text) throws IOException {
String response = request("https://translate.yandex.net/api/v1.5/tr.json/detect?key=" + API_KEY + "&text=" + text);
return response.substring(response.indexOf("lang")+7, response.length()-2);
}
public static String getKey(Map<String, String> map, String value) {
for (String key : map.keySet()) {
if (map.get(key).equalsIgnoreCase(value)) {
return key;
}
}
return null;
}
}