HttpURLConnection乱码问题,求解决?

动量 动量 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面是我的服务端:
@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请求响应的是乱码,使用百度地址返回的响应能正确接收,是不是我的配置有问题???
...全文
评论 10
收藏 已收藏
分享
返回顶部
动量
Android 80,490 成员 91,375 内容