Рубрики
Без рубрики

Как кодировать строку URL или параметр формы в java

– Как кодировать строку URL или параметр формы в java

Это всегда рекомендуется для кодирования параметров URL или формы; параметр простой формы уязвим для межсайтовой атаки, внедрения SQL и может направить наше веб-приложение в некоторые непредсказуемые выходные данные. Строка URL или параметры формы могут быть закодированы с помощью метода URLEncoder class – статическое кодирование (строка s, строка enc).

Например, когда пользователь вводит следующие специальные символы, а ваше веб-приложение не обрабатывает кодировку, это вызовет атаку межсайтового скрипта.

 ]]>

Пример использования URLEncoder для кодирования строки и URLDecoder для декодирования закодированной строки

package com.mkyong;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class testEncode {

  public static void main(String args[]) {

    try {

	String url = " ]]>";

	String encodedUrl = URLEncoder.encode(url, "UTF-8");

	System.out.println("Encoded URL " + encodedUrl);

	String decodedUrl = URLDecoder.decode(url, "UTF-8");

	System.out.println("Dncoded URL " + decodedUrl);

	} catch (UnsupportedEncodingException e) {

		System.err.println(e);

	}
    }
}

Результат

Encoded URL %3C%21%5BCDATA%5B+%3CIMG+SRC%3D%22+%26%2314%3B+
javascript%3Adocument.vulnerable%3Dtrue%3B%22%3E+%5D%5D%3E
Dncoded URL  ]]>

Please remember always encode the URL string and form parameters to prevent all the vulnerability attacks.

Reference

  1. URLEncoder Javadoc
author image
mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

guest
12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
java-coder
java-coder
7 years ago

The post is wrong by saying use URLEncoder for URL parameters. This class is supposed to be used for form parameter encoding and not for url encoding. Space in a url must be encoded as %20 and not as ‘+’. ‘+’ itself should be escaped in URL parameters, it is an unsafe char.

Kristina Mendoza
Kristina Mendoza
4 years ago

Thanks for posting such handy information! Really helped me a bunch.

bahtiaP
bahtiaP
4 years ago

URLEncoder.encode(url, “UTF-8”); is throwing UnsupportedEncodingException

blo
blo
8 years ago

should: String decodedUrl = URLDecoder.decode(url, “UTF-8”); , be: String decodedUrl = URLDecoder.decode(encodedUrl, “UTF-8”);

proving the decoding of the encoded url, not the original url?

neo
neo
8 years ago

Very helpful…!

neo
neo
8 years ago
Reply to  neo

yes..!

Nilam
Nilam
8 years ago

Thanx for solution

http://cancerwecan.com
http://cancerwecan.com
8 years ago

Are you in a position to guidebook me personally for your web marketer or man which looks after your website, I would like to determine it will be easy to be described as a guest poster.

hurelhuyag
hurelhuyag
8 years ago

space must be encoded to %20

trackback
Android java.io.IOException: java.net.URISyntaxException: : Android Community – For Application Development
8 years ago

[…] How to encode url in java […]

Fcrossroad
Fcrossroad
9 years ago

Hello Mkyong, can you explain a little more about how encoding url or form parameters we can prevent some attacks like Sql Injection?

Your post is very good, but i couldn’t undestand this part…

If you prefer only post some links that explain this, would be very helpful too!

fadzz
fadzz
9 years ago

thanks^^…verry simple and help me alot..!!

Оригинал: "https://mkyong.com/java/how-to-encode-a-url-string-or-form-parameter-in-java/"