tags:

views:

6511

answers:

3

Hi, 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.

+3  A: 

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

jgre
So I have to write it like that : encode("hello","x-www-form-urlencoded") or for "x-www-form-urlencoded" it's encode("hello","UTF-8")?
Michaël
You have to write encode("hello","UTF-8"). x-www-form-urlencoded is always the type of the result. The encoding parameter refers to your input data.
jgre
Thank you for your answer!
Michaël
Is there a predefined constant for the possible character encodings?
Janusz
+1  A: 

The JavaDoc has all the details

tg
A: 

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");
URLConnection urlConnection = url.openConnection();
....
....
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" %>
< 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");

Green Techy
I have done :- HttpPost post = new HttpPost("url");- post.setHeader("Content-Type", "application/x-www-form- urlencoded");- String encodedString = URLEncoder.encode("hello","UTF-8");- StringEntity temp;- temp.setContentEncoding(encodedString);- post.setEntity(temp);and then execute a DefaultHttpClient with post for argument.
Michaël
Thank you for your answer!
Michaël
Hope its working now!
Green Techy
The problem was really due to the fact that I put "application/x-www-form-urlencoded" instead of "UTF-8" in encode(String s, String enc)...Again thank you.
Michaël