Android开发之基础-------------Get请求和Post请求

来源:互联网 发布:港口历年数据 编辑:程序博客网 时间:2024/06/06 09:37

向服务器提交请求时,有两种提交方式,下面对这两种提交方式进行简单的整理。

一、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.创建urlURL url = new URL(url_str);//2.获取一个UrlConnectionHttpURLConnection 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.创建urlURL url = new URL(url_str);//2.获取一个UrlConnectionHttpURLConnection 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();}



0 0
原创粉丝点击