[Android note] the android client sends a request to the tomcat server to address Chinese garbled characters.

Source: Internet
Author: User

When the android client requests the url address of the server to contain Chinese characters, Chinese characters are garbled.The cause of garbled characters is as follows:When you request resources on the server in the get method, the Chinese characters in the url are not encoded. 2. Ignored tomcat's default encoding format (iso8859-1 ). 3. The servlet does not set the correct encoding format for the request and response. 4. The servlet does not handle garbled characters in the get request method. Bytes -------------------------------------------------------------------------------------------------Solution: Step: 1,The client encodes the Chinese parameters in the url (using the URLEncoder class ).Here we use the URL provided in the original java.net package and the HTTPURLConnection class. All request data is encapsulated in map.Get request:

/*** Send a request to the server in get mode, and return the response result of the server in string mode. If no response content exists, an empty String ** @ param url request url address * @ param params request parameter * @ param charset url encoding code table * @ return */public static String is returned. getDataByGet (String url, map
 
  
Params, String charset) {if (url = null) {return "";} url = url. trim (); URL targetUrl = null; try {if (params = null) {targetUrl = new URL (url);} else {StringBuilder sb = new StringBuilder (url + "? "); For (Map. Entry
  
   
Me: params. entrySet () {// solve the problem sb. append (me. getKey ()). append ("= "). append (URLEncoder. encode (me. getValue (), charset )). append ("&");} sb. deleteCharAt (sb. length ()-1); targetUrl = new URL (sb. toString ();} Log. I (TAG, "get: url ----->" + targetUrl. toString (); // print log HttpURLConnection conn = (HttpURLConnection) targetUrl. openConnection (); conn. setConnectTimeout (3000); conn. setRequestMethod ("GET"); conn. setDoInput (true); int responseCode = conn. getResponseCode (); if (responseCode = HttpURLConnection. HTTP_ OK) {return stream2String (conn. getInputStream (), charset) ;}} catch (Exception e) {Log. I (TAG, e. getMessage ();} return "";}
  
 
Post request:
/*** Send a request to the server in post mode, and return the response result of the server in string mode. If no response content exists, an empty String * @ param url request url address * @ param params request parameter * @ param charset url encoding code table * @ return */public static String getDataByPost is returned. (String url, map
 
  
Params, String charset) {if (url = null) {return "";} url = url. trim (); URL targetUrl = null; OutputStream out = null; try {targetUrl = new URL (url); HttpURLConnection conn = (HttpURLConnection) targetUrl. openConnection (); conn. setConnectTimeout (3000); conn. setRequestMethod ("POST"); conn. setDoInput (true); conn. setDoOutput (true); StringBuilder sb = new StringBuilder (); if (params! = Null &&! Params. isEmpty () {for (Map. Entry
  
   
Me: params. entrySet () {// encode the Chinese characters in the request data sb. append (me. getKey ()). append ("= "). append (URLEncoder. encode (me. getValue (), charset )). append ("&"); // sb. append (me. getKey ()). append ("= "). append (me. getValue ()). append ("&"); // test found} sb. deleteCharAt (sb. length ()-1);} byte [] data = sb. toString (). getBytes (); conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); conn. setRequestProperty ("Content-Length", String. valueOf (data. length); out = conn. getOutputStream (); out. write (data); Log. I (TAG, "post: url ----->" + targetUrl. toString (); // print log int responseCode = conn. getResponseCode (); if (responseCode = HttpURLConnection. HTTP_ OK) {return stream2String (conn. getInputStream (), charset) ;}} catch (Exception e) {Log. I (TAG, e. getMessage ();} return "";}
  
 
Stream2String method (convert the data in the stream object to a string ):
/*** Output the data in the input stream object to the String and return * @ param in * @ return * @ throws IOException */private static String stream2String (InputStream in, String charset) throws IOException {if (in = null) return ""; byte [] buffer = new byte [1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream (); int len = 0; while (len = in. read (buffer ))! =-1) {bout. write (buffer, 0, len);} String result = new String (bout. toByteArray (), charset); in. close (); return result ;}
During the test, we did find that the Chinese characters in the url in the get request were encoded:

2. The server sets the correct encoding format for the request and response. First, add these lines of code in the servlet.
req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");
This is not complete yet. The above only deals with post request garbled characters, and there are still garbled characters when the user requests in get mode. So you need to add this line of code:
if(req.getMethod().equalsIgnoreCase("GET")){    name = new String(name.getBytes("iso8859-1"),"utf-8");}
The reason why we need to determine whether the request method is get is because if the request method is post, it will become garbled again. Of course, if you perform garbled processing on doPost and doGet respectively in the servlet, you do not need to judge. Most people prefer to write as follows:
public class xxxServlet extends HttpServlet{    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException     {        //TODO        }@Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException    {        this.doGet(req, resp);    }  }
In this case, you must add a judgment in the doget method. Of course, you have another option, that is, the filter. Configure the filter as shown below to process the above garbled characters. The encoding format is manually configured in web. xml to avoid hard encoding. (Configured in context-param)
Package cn.chd.edu. filter; import java. io. IOException; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import javax. servlet. http. httpServle TRequest; import javax. servlet. http. httpServletResponse; public class CharacterEncodingFilter implements Filter {private static String charset = "iso8859-1"; // default encoding public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, servletException {System. out. println ("filter running... "); final HttpServletRequest req = (HttpServletRequest) request; HttpSer VletResponse resp = (HttpServletResponse) response; req. setCharacterEncoding (charset); resp. setCharacterEncoding (charset); resp. setContentType ("text/html; charset =" + charset); chain. doFilter (ServletRequest) Proxy. newProxyInstance (CharacterEncodingFilter. class. getClassLoader (), req. getClass (). getInterfaces (), new InvocationHandler () {public Object invoke (Object proxy, Method method, Object [] args) t Hrows Throwable {if (! Method. getName (). equals ("getParameter") // intercept the getParameter method {return method. invoke (req, args);} if (! Req. getMethod (). equalsIgnoreCase ("get") // intercept get request {return method. invoke (req, args);} String value = (String) method. invoke (req, args); if (value = null) return null; return new String (value. getBytes ("iso8859-1"), charset) ;}}, resp);} public void init (FilterConfig filterConfig) throws ServletException {String temp = filterConfig. getServletContext (). getInitParameter ("charset"); if (temp! = Null) charset = temp;} public void destroy (){}}
For details about filter, refer to this article: filter



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.