俄语语言引发IOException。

huangapple go评论79阅读模式
英文:

Russian language causing IOException

问题

我正在使用这个 API https://dictionaryapi.dev/ 来制作适用于Google字典的机器人。它应该能够显示不同语言的单词定义。并且对于英语和西班牙语,机器人都正常工作。但是每次我输入俄语单词时都会出现 IOException 错误。可能的原因是什么?

这是我的 Bot 类。
Bot.java:

public void onUpdateReceived(Update update) {
    // Model model = new Model();
    WordModel wordModel = new WordModel();
    Message message = update.getMessage();
    if (message != null && message.hasText()) {
        switch (message.getText()) {
            case "/english":
                DictionaryEntry.setLanguage("en");
                sendMsg(message, DictionaryEntry.getLanguage());
                break;
            case "/russian":
                DictionaryEntry.setLanguage("ru");
                sendMsg(message, DictionaryEntry.getLanguage());
                break;
            case "/spanish":
                DictionaryEntry.setLanguage("es");
                sendMsg(message, DictionaryEntry.getLanguage());
                break;
            default:
                if (!message.getText().contains("/")) {
                    try {
                        sendMsgs(message, DictionaryEntry.getWords(message.getText(), wordModel));
                    } catch (IOException e) {
                        sendMsg(message, "Not found");
                        sendMsg(message, DictionaryEntry.getUrl().toString());
                    }
                }
                break;
        }
    }
}

public void sendMsg(Message message, String text) {
    SendMessage sendMessage = new SendMessage();
    sendMessage.setChatId(message.getChatId());
    sendMessage.setReplyToMessageId(message.getMessageId());
    sendMessage.setText(text);
    try {
        // setButtons(sendMessage);
        execute(sendMessage);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

public void sendMsgs(Message message, List<String> words) {
    for (int i = 0; i < words.size(); i++) {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(message.getChatId());
        sendMessage.setReplyToMessageId(message.getMessageId());
        sendMessage.setText(words.get(i));
        try {
            // setButtons(sendMessage);
            execute(sendMessage);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

这是我处理从 URL 获取的 JSON 字符串的 DictionaryEntry 类。
DictionaryEntry.java:

private static String language = "ru";

public static String getLanguage() {
    return language;
}

public static void setLanguage(String language) {
    DictionaryEntry.language = language;
}

public static URL getUrl() {
    return url;
}

private static URL url;

public static List<String> getWords(String message, WordModel wordModel) throws IOException {
    url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
            + DictionaryEntry.getLanguage() + "/" + message);

    Scanner in = new Scanner((InputStream) url.getContent());
    String result = "";

    while (in.hasNext()) {
        result += in.nextLine();
    }

    String result2 = result.replaceAll("\"", "\\\"");

    List<WordModel> models = new ArrayList<>();
    List<String> results = new ArrayList<>();
    int count = 0;

    try {
        JSONArray mainArray = new JSONArray(result2);

        for (int i = 0; i < mainArray.length(); i++) {
            JSONObject wordEntry = mainArray.getJSONObject(i);
            String wordName = wordEntry.getString("word");
            wordModel.setWord(wordName);

            JSONArray meaningsArray = wordEntry.getJSONArray("meanings");
            for (int j = 0; j < meaningsArray.length(); j++) {
                JSONObject meaningEntry = meaningsArray.getJSONObject(j);
                JSONArray definitionsArray = meaningEntry.getJSONArray("definitions");
                for (int k = 0; k < definitionsArray.length(); k++) {
                    // count++;
                    JSONObject definitionEntry = definitionsArray.getJSONObject(k);
                    String definition = definitionEntry.getString("definition");
                    wordModel.setDefinition(definition);

                    if (definitionEntry.has("example")) {
                        count++;
                        String example = definitionEntry.getString("example");
                        wordModel.setExample(example);
                    } else {
                        wordModel.setExample("No examples found");
                    }

                    models.add(wordModel);
                    results.add("Word: " + wordModel.getWord() + "\n\n" +
                            "Definition: " + wordModel.getDefinition() + "\n\n" +
                            "Example: " + wordModel.getExample());
                }
            }
        }

        /*result = "Word: " + wordModel.getWord() + "\n\n" +
                 "Definition: " + wordModel.getDefinition() + "\n\n" +
                 "Example: " + wordModel.getExample();*/
    } catch (JSONException e) {
        count = 50;
    }

    results.add(url.toString());

    return results;
}

以下是堆栈跟踪:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.dictionaryapi.dev/api/v2/entries/ru/мышь
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
    at java.base/java.net.URLConnection.getContent(URLConnection.java:749)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:404)
    at java.base/java.net.URL.getContent(URL.java:1181)
    at DictionaryEntry.getWords(DictionaryEntry.java:73)
    at Bot.onUpdateReceived(Bot.java:91)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:321)
英文:

I'm making the bot for Google Dictionary using this API https://dictionaryapi.dev/. It's supposed to show word definitions in different languages. And the bot works just fine for English and Spanish. But there's an IOException every time I put in Russian words. What can be the cause of it?

Here's my Bot class.
Bot.java:

public void onUpdateReceived(Update update) {
//Model model = new Model();
WordModel wordModel = new WordModel();
Message message = update.getMessage();
if (message != null &amp;&amp; message.hasText())
{
switch (message.getText()) {
case &quot;/english&quot;:
DictionaryEntry.setLanguage(&quot;en&quot;);
sendMsg(message, DictionaryEntry.getLanguage());
break;
case &quot;/russian&quot;:
DictionaryEntry.setLanguage(&quot;ru&quot;);
sendMsg(message, DictionaryEntry.getLanguage());
break;
case &quot;/spanish&quot;:
DictionaryEntry.setLanguage(&quot;es&quot;);
sendMsg(message, DictionaryEntry.getLanguage());
break;
default:
if (!message.getText().contains(&quot;/&quot;)) {
try {
sendMsgs(message, DictionaryEntry.getWords(message.getText(), wordModel));
} catch (IOException e) {
sendMsg(message, &quot;Не найдено&quot;);
sendMsg(message, DictionaryEntry.getUrl().toString());
}
}
break;
}
}
}
public void sendMsg(Message message, String text) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
public void sendMsgs(Message message, List&lt;String&gt; words) {
for (int i = 0; i &lt; words.size(); i++) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(words.get(i));
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}

And here's my DictionaryEntry class where I process JSON string that I get from URL.
DictionaryEntry.java:

private static String language = &quot;ru&quot;;
public static String getLanguage() {
return language;
}
public static void setLanguage(String language) {
DictionaryEntry.language = language;
}
public static URL getUrl() {
return url;
}
private static URL url;
public static List&lt;String&gt; getWords(String message, WordModel wordModel) throws IOException {
url = new URL(&quot;https://api.dictionaryapi.dev/api/v2/entries/&quot;
+ DictionaryEntry.getLanguage() + &quot;/&quot; + message);
Scanner in = new Scanner((InputStream) url.getContent());
String result = &quot;&quot;;
while (in.hasNext())
{
result += in.nextLine();
}
String result2 = result.replaceAll(&quot;\&quot;&quot;, &quot;\\\&quot;&quot;);
List&lt;WordModel&gt; models = new ArrayList&lt;&gt;();
List&lt;String&gt; results = new ArrayList&lt;&gt;();
int count = 0;
try {
JSONArray mainArray = new JSONArray(result2);
for (int i = 0; i &lt; mainArray.length(); i++) {
JSONObject wordEntry = mainArray.getJSONObject(i);
String wordName = wordEntry.getString(&quot;word&quot;);
wordModel.setWord(wordName);
JSONArray meaningsArray = wordEntry.getJSONArray(&quot;meanings&quot;);
for (int j = 0; j &lt; meaningsArray.length(); j++) {
JSONObject meaningEntry = meaningsArray.getJSONObject(j);
JSONArray definitionsArray = meaningEntry.getJSONArray(&quot;definitions&quot;);
for (int k = 0; k &lt; definitionsArray.length(); k++) {
//count++;
JSONObject definitionEntry = definitionsArray.getJSONObject(k);
String definition = definitionEntry.getString(&quot;definition&quot;);
wordModel.setDefinition(definition);
if (definitionEntry.has(&quot;example&quot;)) {
count++;
String example = definitionEntry.getString(&quot;example&quot;);
wordModel.setExample(example);
}
else {
wordModel.setExample(&quot;No examples found&quot;);
}
models.add(wordModel);
results.add(&quot;Word: &quot; + wordModel.getWord() + &quot;\n\n&quot; +
&quot;Definition: &quot; + wordModel.getDefinition() + &quot;\n\n&quot; +
&quot;Example: &quot; + wordModel.getExample());
}
}
}
/*result = &quot;Word: &quot; + wordModel.getWord() + &quot;\n\n&quot; +
&quot;Definition: &quot; + wordModel.getDefinition() + &quot;\n\n&quot; +
&quot;Example: &quot; + wordModel.getExample();*/
} catch (JSONException e) {
count = 50;
}
results.add(url.toString());
return results;
}

Here's the stack trace:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.dictionaryapi.dev/api/v2/entries/ru/мышь
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
at java.base/java.net.URLConnection.getContent(URLConnection.java:749)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:404)
at java.base/java.net.URL.getContent(URL.java:1181)
at DictionaryEntry.getWords(DictionaryEntry.java:73)
at Bot.onUpdateReceived(Bot.java:91)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:321)

答案1

得分: 1

+ URLEncoder.encode(message, "UTF-8")

你正在发送一个HTTP请求URL应该适用于所使用的编码方式

在使用正确的字符集/编码方面还有更多要考虑的地方但这可能已经足够了该网站可能使用UTF-8因为它可以处理完整的Unicode范围

400是错误的请求

------------------

url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
            + DictionaryEntry.getLanguage() + "/"
            + URLEncoder.encode(message, "UTF-8"));

以及

Scanner in = new Scanner((InputStream) url.getContent(),
    StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNextLine())
{
    sb.append(in.nextLine()).append('\n');
}
String result = sb.toString();
英文:
+ URLEncoder.encode(message, &quot;UTF-8&quot;)

You are sending a HTTP request. The URL should be appropriate for the used encoding.

There are more aspects of using the right charset/encoding, but this might already be sufficient. The site probably uses UTF-8, as that can handle the full Unicode range.

400 is BAD REQUEST.


url = new URL(&quot;https://api.dictionaryapi.dev/api/v2/entries/&quot;
+ DictionaryEntry.getLanguage() + &quot;/&quot;
+ URLEncoder.encode(message, &quot;UTF-8&quot;));

And

    Scanner in = new Scanner((InputStream) url.getContent(),
StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNextLine())
{
sb.append(in.nextLine()).append(&#39;\n&#39;);
}
String result = sb.toString();

答案2

得分: -1

请在您的环境中检查文件是否以utf-8u格式存储,因为可能不支持Cyrillic字符。

英文:

Check in your environment that the file was in utf-8u format Because Cyrillic may not be supported

huangapple
  • 本文由 发表于 2020年9月14日 18:27:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63882499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定