老罗视频学习。
本例从客户端提交数据给服务器,服务器接收到数据之后,看是否匹配,匹配返回字符串“login is success!”,失败返回“login is error!”
一.客户端。
初始化url地址
private static String path = "http://192.168.10.102:8080/myhttp/servlet/LoginActivity";
private static URL url;
static{
try {
url = new URL(path);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setPostMessage函数
getOutputStream是向服务器传递数据用的。
getInputStream是从服务器获取数据用的。
向服务器输入数据传递图片之类的,要用HttpUrlConnection类
doInput默认值是true,doOutput默认值是false。
private static String sendPostMessage(Map<String, String> params,String encode) {
//请求体封装在StringBuffer中
StringBuffer buffer = new StringBuffer();
//buffer.append("?");
try {
//判断是否为空
if(params!=null && !params.isEmpty()){
//迭代for循环
for(Map.Entry<String, String> entry : params.entrySet()){
//append,追加字符串
buffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(),encode))
.append("&");
}
}
//删掉最后多余的那个“&”
buffer.deleteCharAt(buffer.length()-1);
System.out.print(buffer.toString());
//接下来是http协议内容
//打开链接
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//设置服务器断开重连时间
urlConnection.setConnectTimeout(3000);
//设置提交方式
urlConnection.setRequestMethod("POST");
//设置从服务器读取数据
urlConnection.setDoInput(true);
//设置向服务器写数据
urlConnection.setDoOutput(true);
//接下来需要把url的请求的内容,封装到一个请求体中
//获得上传信息的字节大小
byte[] data = buffer.toString().getBytes();
//设置请求体的类型
//设置请求体类型为文本类型,暂时不涉及图片及二进制数据
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//获得输出流,向服务器输出数据
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(data,0,data.length);
outputStream.close();
//获得服务器响应的结果和状态码
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
//把inputStream改为String传递出来
return ChangeInputStream(urlConnection.getInputStream(),encode);
}
}catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
changeInputStream函数如下:
把InputStream以encode格式转换为String
private static String ChangeInputStream(InputStream inputStream,
String encode) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String resultString = "";
if(inputStream!=null) {
try {
//数据循环存储在outputStream中
while ((len=inputStream.read(data))!=-1) {
outputStream.write(data,0,len);
}
//首先转换为字节数组,然后以encode编码格式转换为字符串
resultString = new String(outputStream.toByteArray(),encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
测试main函数如下:
public static void main(String[] args) {
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "123");
String encode = "utf-8";
String resString = HttpUrils.sendPostMessage(params, encode);
System.out.print("------>"+resString);
}
二.服务器端,还用get方式例子里用到的服务器。
LoginActivity继承自HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//设置编码格式
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//获取用户名username,密码password
PrintWriter out = resp.getWriter();
String usernameString = req.getParameter("username");
String pswdString = req.getParameter("password");
System.out.print(usernameString);
System.out.print(pswdString);
//匹配成功
if(usernameString.equals("admin")&&pswdString.equals("123")){
out.print("login is success!");
}//匹配不成功
else {
out.print("login is error!");
}
out.flush();
out.close();