向服务器提交请求时,有两种提交方式,下面对这两种提交方式进行简单的整理。
一、get方式 和 post方式 请求服务器的区别:
1. 请求的url地址不同
get:http://kr41m1i4fwt359b:8080/itheima75/servlet/LoginServlet?username=root&pwd=123
post:http://kr41m1i4fwt359b:8080/itheima75/servlet/LoginServlet
2. 请求头不同,post请求多了4个请求头和一个请求内容
Content-Length: 21
Cache-Control: max-age=0
Origin: http://kr41m1i4fwt359b:8080
Content-Type: application/x-www-form-urlencoded
username=root&pwd=123
3. 请求时携带数据大小不同
get:1k
post:理论上无限制
1.get请求实例代码:
String url_str = "http://192.168.20.82:8080/itheima75/servlet/LoginServlet?username="+username+"&pwd="+password;
try{
//1.创建url
URL url = new URL(url_str);
//2.获取一个UrlConnection
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
//3.设置参数
openConnection.setRequestMethod("GET");
openConnection.setConnectTimeout(10*1000);
//4.获取状态码,判断
if(openConnection .getResponseCode() == 200){
//5.获取流信息,转换字符串
InputStream inputStream = openConnection.getInputStream();
String result = StreamUtils.streamToString(inputStream);
Message msg = Message.obtain();
msg.obj = result;
handler.sendMessage(msg);
//6.关流,关连接
inputStream.close();
openConnection.disconnect();
}
}catch (Exception e) {
e.printStackTrace();
}
2.post请求实例代码:
String url_str = "http://192.168.20.82:8080/itheima75/servlet/LoginServlet";
try{
//1.创建url
URL url = new URL(url_str);
//2.获取一个UrlConnection
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
//3.设置参数 ,设置一些请求头
openConnection.setRequestMethod("POST");
openConnection.setConnectTimeout(10*1000);
String content = "username="+username+"&pwd="+password;//拼装请求时携带的数据
openConnection.setRequestProperty("Content-Length", content.length()+"");//设置请求头 field:请求头的key,newValue :请求头的值
openConnection.setRequestProperty("Cache-Control", "max-age=0");
openConnection.setRequestProperty("Origin", "http://192.168.20.82:8080");
openConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置当前的UrlConnection可以上传主题内容。
openConnection.setDoOutput(true);
//获取UrlConnection的一个写入流将主题内容写入,上传
openConnection.getOutputStream().write(content.getBytes());
//4.获取状态码,判断
if(openConnection .getResponseCode() == 200){
//5.获取流信息,转换字符串
InputStream inputStream = openConnection.getInputStream();
String result = StreamUtils.streamToString(inputStream);
Message msg = Message.obtain();
msg.obj = result;
handler.sendMessage(msg);
//6.关流,关连接
inputStream.close();
openConnection.disconnect();
}
}catch (Exception e) {
e.printStackTrace();
}