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
It seems that the content in Array[i] comes from a html input element. I suspect there is some kind of whitespace such as \r\n
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: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();
}
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!
The @ character must be encoded. Eg replace it directly with %40. but you can also use
URLEncoder.encode(s,"UTF-8")
I have changed your code,could you please run and test it
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);
url= new URL(URLEncoder.encode(urlString, "UTF-8"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection conn = url.openConnection();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.