我们知道Android向服务器提交数据有很多方式,本文作者常用的是 模拟Http协议使用get或者post方式来提交。这时候如果提交的数据为中文,势必牵扯到乱码问题。
网上也有很多种方式(包括设置统一编码,或者对中文进行URL编码),也许是本文作者前期编码设置不一样,经过适用之后却只有一种可行。 就是将get方式改变为post方式来解决这个问题,附上android端与tomcat代码,希望能为初学android的朋友带来点帮助。
下面是Android客户端与Tomcat服务端使用的一个工具类代码,需要在下文中用到:
public class StreamTool { //从输入流中读取数据 public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = inStream.read(buffer)) !=-1 ){ outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); } }
下面为post方式从Android向服务器提交数据代码,注意“conn.setRequestProperty”这个地方public static String getPatients(String keShi) { String path1 = "http://192.168.1.226:8181/HPPatient/servlet/DBService1"; try { byte[] data = (keShi).getBytes(); URL url = new URL(path1); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text;charset=UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.getOutputStream().write(data); //得到响应吗 if (conn.getResponseCode() == 200) { InputStream inStream = conn.getInputStream(); byte[] data1 = StreamTool.readInputStream(inStream); inStream.close(); return new String(data1, "GBK"); } return "NetError"; } catch (Exception e) { return "NetError"; } }
下面为Tomcat服务器端接收代码:注意接收时为UTF-8,作者曾将两端编码统一为其他编码格式例如GBK,都呈现乱码问题。public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getInputStream() != null) { try { //这样既可解决乱码 String keShi = new String(StreamTool.readInputStream(request.getInputStream()),"UTF-8"); //下面读者不必理会 String data = DBUtils.getMessage(keShi); OutputStream out = response.getOutputStream(); out.write(data.getBytes()); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }