HttpURLConnection乱码问题,求指导决

Android 码拜 9年前 (2016-03-23) 917次浏览
下面是本人的服务端:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		Enumeration<String> e=req.getHeaderNames();
		while(e.hasMoreElements()){
			String key=e.nextElement();
			System.out.println(key+"="+req.getHeader(key));
		}
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
		String name=req.getParameter("name");
		if("kaiqi".equals(name)){
			System.out.println("通过验证");
			out.println("<html><head><title></title></head><body>successed<body></html>");
		}else{
			System.out.println("验证未通过");
			out.println("<html><head><title></title></head><body>failed<body></html>");
		}

	}
}

下面是本人的android客户端,只有一个按钮控件:

public class MainActivity extends AppCompatActivity {
    private Button loginBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loginBtn=(Button)findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    @Override
                    public void run() {
                        String urlStr="http://192.168.1.101:8080/AndroidNetTest/user?name=kaiqi";
                         //String urlStr="http://www.baidu.com";
                        try {
                            URL url=new URL(urlStr);
                            HttpURLConnection con= (HttpURLConnection) url.openConnection();
                            InputStream in=con.getInputStream();
                            byte[] buf=new byte[1024];
                            in.read(buf);
                            Log.i("wjq",new String(buf,"utf-8"));
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
    }
}

发送get请求响应的是乱码,使用百度地址返回的响应能正确接收,是不是本人的配置有问题?

解决方案

40

输出的时候再转一下utf-8的,sting.getbytes(“utf-8”)

20

问问你服务端的编码是什么,要和服务端使用的编码一样

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明HttpURLConnection乱码问题,求指导决
喜欢 (0)
[1034331897@qq.com]
分享 (0)