skip to Main Content

I’m sending a message to telegram channel and i have error

Simple string sent, but modified by the type of part of the array is not sent

 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();

Exception in thread “main” java.net.MalformedURLException: Illegal character in URL

2

Answers


  1. The @ character must be encoded. E.g. replace it directly with %40.
    but you can also use

    URLEncoder.encode(s,"UTF-8")
    
    Login or Signup to reply.
  2. It seems that the content in Array[i] comes from a html input element. I suspect there is some kind of whitespace such as rn that is passed to the URL, which then causes the MalformedURLException.

    Here my approach:

        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:00rn13:00rn14:00rn";
    
            // Split by carriage return
            String timeTokens[] = timeHtmlInput.split("rn");
    
            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();
        }
    
    

    BTW it is always good practice to encode the query string parameters, such as:

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

    as they also might contain some other illegal characters.
    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search