Yandex Api在日食中无法正常翻译

时间:2018-09-25 02:38:51

标签: java yandex

Here is my code in TranslateAPI.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
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 = "pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a";

        private static String request(String URL) throws IOException {
            URL url = new URL(URL);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();


            InputStream inStream = urlConn.getInputStream();

            String recieved = new BufferedReader(new InputStreamReader(inStream)).readLine();

    System.setProperty("http.agent", "Chrome");
            String agent = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("http.agent"));
            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);
        }

AND in workerthread.java:
String s=TranslateAPI.detectLanguage(abc);
                            System.out.println(s);

但是,我遇到了以下错误:

服务器返回HTTP响应代码:403,URL:https://translate.yandex.net/api/v1.5/tr.json/detect?key=pdct.1.1.20180924T090857Z.3e14b8b207704aef.9bdc409229b123003526815bb7062ed42616f26a&text=cat 你能帮忙吗?预先感谢

1 个答案:

答案 0 :(得分:0)

您收到 401错误,因此您的API密钥无效

您随时可以转到Yandex's Developers page来获得一个新的。

在此处发布您的私有API 总是很不错的:D