Get与Post提交与中文乱码解决

android客户端请求服务端的url地址中含有中文时将会产生中文乱码问题。
产生乱码的原因有主要以下几个方面:
1.当以get方式请求服务端的资源时,没有对url中的中文进行编码。
2.忽略了tomcat默认的编码格式(iso8859-1)。
3.servlet没有对request和response设置正确的编码格式。
4.servlet没有处理get请求方式中的乱码问题。
解决方案:
GET请求

public static String LoginByGet(String username, String pwd) {

        try {
            //URLEncoder解决中文乱码
            String path = "http://192.168.51.21:8080/Page/login?username=" +
                    URLEncoder.encode(username,"utf-8") + "&password=" +URLEncoder.encode(pwd,"utf-8") ;
            URL url = new URL(path);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5000);
            con.setRequestMethod("GET");
            int code = con.getResponseCode();
            if(code==200){
                InputStream is=con.getInputStream();
                String res;
                res = StreamTools.ReadInputStream(is);
                return res;
            }else{
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

POST请求:

 public static String LoginByPost(String username, String pwd) {
        String path = "http://192.168.51.21:8080/Page/login";
        try {
            URL url = new URL(path);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5000);
            con.setRequestMethod("POST");

            String data="username=" + username +"&password=" + pwd;
            //设置post请求必要的请求头
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Length",data.getBytes().length+"");//length必须是字符串二进制的长度

            con.setDoOutput(true);//准备写出
            OutputStream os=con.getOutputStream();
            os.write(data.getBytes("utf-8"));//向浏览器写数据,并设置编码格式
            int code = con.getResponseCode();
            if(code==200){
                InputStream is=con.getInputStream();
                String res= StreamTools.ReadInputStream(is);
                return res;
            }else{
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

得到响应数据的处理ReadInputStream类


public class StreamTools {
    public static String ReadInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream bayo = new ByteArrayOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            bayo.write(buffer, 0, len);
        }
        is.close();
        bayo.close();
        byte[] res=bayo.toByteArray();
        String str=new String(res);
        return str;
    }
}

WEB服务器端

package com.haitun.example;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //服务端对request和response设置正确的编码格式
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        //之所以要判断一下请求的方式是是否为get,是因为如果请求方式
        //为post的话,又会变成乱码
        if(request.getMethod().equalsIgnoreCase("get")){
            username=new String(username.getBytes("ISO-8859-1"),"utf-8");
        }
        System.out.println(username);
        PrintWriter out= response.getWriter();
        if(password.equals("123")){
            out.print("success");
        }else{
            out.print("失败");
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub
        this.doGet(request, response);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值