我如何发送这样的字符串?

时间:2019-11-08 08:05:42

标签: java 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中的非法字符

2 个答案:

答案 0 :(得分:0)

@字符必须被编码。例如。直接将其替换为%40。 但您也可以使用

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

答案 1 :(得分:0)

似乎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"));

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