本帖最后由 fighting 于 2013-3-16 20:03 编辑
在android中经常使用httpclient与网络连接,但是我当我用java app写了一个表单验证时,提交中文数据时出现了问题:
在使用post方式提交时,先对中文进行编码,当在servlet中获取时,tomcat貌似并没有对这些编码进行解码,不知是什么原因?
这是post方法,用于提交数据- //使用httpclient-post的方式提交数据,为什么当请求中有中文时在服务器端取不自动解码呢???
- public String httpclientPostToServer(String username, String password){
- String info = null;
-
- try {
- username = URLEncoder.encode(username, "utf-8");
- password = URLEncoder.encode(password, "utf-8");
-
- HttpPost post = new HttpPost(Config.site);
-
- List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
- list.add(new BasicNameValuePair("username", username));
- list.add(new BasicNameValuePair("password", password));
-
- post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
-
- DefaultHttpClient httpclient = new DefaultHttpClient();
- HttpResponse response = httpclient.execute(post);
-
- if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
- InputStream is = response.getEntity().getContent();
-
- info = streamToString(is);
- }else{
- System.out.println("服务器返回异常");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return info;
- }
复制代码 这是servlet- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String username = request.getParameter("username");
- String password = request.getParameter("password");
-
- //注意编码集的统一
- username = new String(username.getBytes("iso-8859-1"), "utf-8");
- password = new String(password.getBytes("iso-8859-1"), "utf-8");
-
- // 假定参数不为空
- System.out.println("username:" + username + "\npassword:" + password);
- if ("川".equals(username) && "123".equals(password)) {
- response.getOutputStream().write("登录成功!".getBytes());
- } else {
- response.getOutputStream().write("登录失败!".getBytes());
- }
- }
复制代码 问题在代码中也表明了,输出的结果是:
username:%E5%B7%9D
password:123
|