我如何将数组字符串发送到电报?

How i can send array strings to telegram?

我正在向电报频道发送消息,但出现错误

简单的字符串发送,但是被类型修饰的部分数组没有发送

 String urlString = "https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s";

    String apiToken = "123843242734723";
    String chatId = "@Example";
    String text = Array[i]+ " hello";

    urlString = String.format(urlString, apiToken, chatId, text);

    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    URLConnection conn = url.openConnection();

线程中的异常 "main" java.net.MalformedURLException: URL

中的非法字符

必须对@ 字符进行编码。例如。直接用 %40 替换它。 但你也可以使用

URLEncoder.encode(s,"UTF-8")

Array[i] 中的内容似乎来自 html 输入元素。我怀疑有某种空白,例如 \r\n 被传递给 URL,然后导致 MalformedURLException.

这里是我的方法:

    public static void main(String[] args) throws IOException {
        // Here is where you would assign the content of your HTML element
        // I just put a string there that might resemble what you get from your HTML
        String timeHtmlInput = "12:00\r\n13:00\r\n14:00\r\n";

        // Split by carriage return
        String timeTokens[] = timeHtmlInput.split("\r\n");

        String urlString = "https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s";
        String apiToken = "123843242734723";
        String chatId = "@Example";
        String time = timeTokens[0];
        String text = time + "Hello";

        urlString = String.format(urlString, 
                URLEncoder.encode(apiToken, "UTF-8"), 
                URLEncoder.encode(chatId, "UTF-8"),
                URLEncoder.encode(text, "UTF-8"));

        URL url = new URL(urlString);
        System.out.println(url);
        URLConnection conn = url.openConnection();
    }

顺便说一句,最好对查询字符串参数进行编码,例如:

URLEncoder.encode(text, "UTF-8"));

因为它们还可能包含其他一些非法字符。 希望这对您有所帮助!