首页 > 代码库 > android中的HttpUrlConnection的使用之四

android中的HttpUrlConnection的使用之四

 前面的使用之三我简单的说了下app与本地的服务器相连接并进行简单的数据传输,但是后来简单的测试了一下传输中文数据,会发现乱码了!这是怎么回事呢?这里我们解释一下出现这个情况的原因。

1.首先分析原因:这是因为当我们提交数据时,数据编码格式是iso-8859-1,而服务器那边数据的编码格式是utf-8格式。因此我们想不会出现这种情况的话,必须进行数据转码

2.数据转码:服务器后台收到数据我们应该使用相应的方法,将原来的数据格式从iso-8859-1格式转化为utf-8.

Java代码(这个是servlet的Java代码 是服务器的代码,不是客户端)
 1 package com.Servlet; 2  3 import java.io.IOException; 4 import java.io.PrintWriter; 5  6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse;10 11 /**12  * Servlet implementation class Servlet13  */14 public class Servlet extends HttpServlet {15     private static final long serialVersionUID = 1L;16        17     /**18      * @see HttpServlet#HttpServlet()19      */20     public Servlet() {21         super();22         // TODO Auto-generated constructor stub23     }24 25     /**26      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)27      */28     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {29         //调用下面的doPost方法30         this.doPost(request, response);31     }32 33     /**34      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)35      */36     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {37         //从request中分别获得name age属性38         String name = request.getParameter("name");39         String age = request.getParameter("age");40         response.setContentType("text/html;charset=utf-8");41         PrintWriter pw = response.getWriter();42         //再网页上显示相应的信息43         System.out.println(new String (name.getBytes("iso-8859-1"), "UTF-8"));44         pw.println("name = " + new String (name.getBytes("iso-8859-1"), "UTF-8") + " age = " + age);45         //在控制上显示相应的信息46         System.out.println("11name = " + new String(name.getBytes("iso-8859-1"), "utf-8"));47         System.out.println("age = " + age);48     }49 50 }

将代码改成这样过后,我们再去测试,如果发现在网页显示的是正确的,而控制台上显示的却是乱码。这个是为什么呢?

那是因为在编码的时候, jsp文件按照的是iso-8859-1的格式编码,因此要改变它的编码格式。只需将下面的红色部分改变了就是了。

jsp代码

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="ISO-8859-1"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body>10 11     <form action="Servlet" method = "get">12     name:<input type = "text" name = "name"><br>13     age:<input type = "text" name = "age"><br>14     submit:<input type = "submit" value = "http://www.mamicode.com/submit"><br>15     </form>16 </body>17 </html>

 

android中的HttpUrlConnection的使用之四