Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLEncoder encode / URLDecoder decode in java (Android)

Tags:

java

android

I want to use the URLEncoder/URLDecoder class (java.net.URLEncoder/URLDecoder) in an application and the methods : encode(String s, String enc)/decode(String s, String enc), but I don't know what can be the value of the String argument enc? I want to encode/decode in the "x-www-form-urlencoded" MIME content type. Thank you for your help.

like image 204
Michaël Avatar asked May 22 '09 07:05

Michaël


People also ask

What is URLEncoder encode in Java?

public class URLEncoder extends Object. Utility class for HTML form encoding. This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format. For more information about HTML form encoding, consult the HTML specification.

What does Urldecoder decode do?

decode. Decodes a application/x-www-form-urlencoded string using a specific encoding scheme. The supplied encoding is used to determine what characters are represented by any consecutive sequences of the form " %xy ". Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used.

How do I stop URL encoding?

You can decode the url using javascript Function: decodeURIComponent(Url ); Because Browser encodes the Url for special characters . For example : https://www.example.com is encoded to %20https%3A%2F%2Fwww.example.com. Here the special characters are replaced by % and its ASCI value.


2 Answers

The encoding parameter is the character encoding you're using. For example "UTF-8".

like image 129
jgre Avatar answered Oct 05 '22 22:10

jgre


First you need to set the content-type as a 'x-www-form-urlencoded'. Then whatever content you would like to encode, encode it using "UTF-8".

For example:

For setting content to 'x-www-form-urlencoded':

URL url = new URL("http://www.xyz.com/SomeContext/SomeAction"); <br>
URLConnection urlConnection = url.openConnection();<br>
....<br>
....<br>
urlConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded");


Or if you are using some JSP then you can write the following on top of it.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><br>
< META http-equiv="Content-Type" content="text/html; charset=UTF-8">


< FORM action="someaction.jsp" enctype="application/x-www-form-urlencoded" name="InputForm" method="POST">

And to use URLEncoder:

String encodedString = URLEncoder.encode("hello","UTF-8");
like image 43
Sourabh Avatar answered Oct 05 '22 23:10

Sourabh