1构建web工程
新建web dynamic项目在login.jsp body体随便写一些中文
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="submit">
</form>
<form action="LoginServlet" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
然后右击login.jsp run on Server
2构建Android客户端 客户端代码见上一篇日志
注意网址改为http://自己的ip:8080/web项目名称/login.jsp
自己的ip在cmd输入ipconfig查询
注意:如果使用真机实验 可能是由于不在一个网段 无法获取数据,因此要使用Wifi共享软件让手机连上Wifi在访问,此时使用上图中第一个ip(无线ip)
如果使用虚拟机则是使用第二个ip(本地ip)
虚拟机测试结果
修改web端的login.jsp的所有编码为gbk(三处) 则从服务器下载的中文是乱码
<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="submit">
</form>
<form action="LoginServlet" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Android下默认charset为utf-8
因此Android端工具类20行
return new String(result);
其实是
return new String(result,"utf-8");
改进方法修改工具类如下:
package com.example.a52_htmlviewer.tools;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTools {
//把输入流转化成字符串
public static String readInputStream(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte [] buffer = new byte [1024];
while ((len = is.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
is.close();
baos.close();
byte [] result = baos.toByteArray();
//试着解析xml文件 看看编码集是什么
String temp = new String(result);
//正规时应该使用正则表达式 这里只做简单判断
if (temp.contains("utf-8")) {
return temp;
}else if(temp.contains("gbk")) {
return new String(result,"gbk");
}else if(temp.contains("iso-8859-1")) {
return new String(result,"iso-8859-1");
}else if(temp.contains("gb2312")) {
return new String(result,"gb2312");
}else {
return temp;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "获取失败";
}
}
}