蒟蒻のJAVA小窝(httpservletrequst的字节流编码问题)待解决*

getInputStream,返回是一个输入流对象,读取的是时候需一行一行去读,但是这个获取内容,如果表单数据有中文,很容易发生编码的问题。

1.ServletDemo4.java内容

package com.anthony.servlet;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.anthony.entity.User;

public class ServletDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");        // 通过字节流方法获取表单数据    
        ServletInputStream sis = req.getInputStream();
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = sis.read(b)) != -1) {
            System.out.println(new String(b, "UTF-8"));
        }
        sis.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

然而输出的全是乱码。。

userName=Anthony&pwd=13433454&gender=%E7%94%B7&hobby=%E7%AF%AE%E7%90%83&hobby=%E5%94%B1%E6%AD%8C&hobby=%E7%BC%96%E7%A0%81&city=gz

2.解决乱码

网上找了很多办法,什么StringBuilder都不行,原因就是请求头中 Accept-Encoding的值为gzip格式,中文就是无法解析。这个问题先放这里,以后找到答案再来更新。

发布了20 篇原创文章 · 获赞 13 · 访问量 549

猜你喜欢

转载自blog.csdn.net/weixin_45961841/article/details/104913746