19 May 2010

request.getCharacterEncoding() always returns null

Alsalamo Alykom,

If you suffer from this problem, so this is the place you need to visit!

Well, you need to get the character encoding of the request sender in Servlets and you have tried using this method again and again but without any results!

So, this is not the problem of the Servlets, It is the problem of the browser you use!

Yes, try the following code to make sure that the Servlet engine can interpret the character encoding of your request, but only when they are really sent

the following code written suing Commons-http, and need commons-logging and commons-codes:

package com.forat;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class Client {
public static void main(String[] args) throws IOException{
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod("http://localhost:8080/aServer/AServlet");
method.setRequestHeader("Content-Type", "text/plain; charset=GB2312");
client.executeMethod(method);
}
}


And here's the Servlet code:

package com.forat;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class AServlet
*/
public class AServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getCharacterEncoding());
}

}



And here's the output:
GB2312


For Firefox, try Firebug to make sure that firefox doesn't send the Content-Type as a request header even if you set.

Here's a sample HTML page that sends to the same above servlet:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>
<body>

<form action="AServlet" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>


and the result of the servlet is:
null


And here's a screenshot from Firebug displaying all request header but doens't display Content-type.

No comments: