Android实现Get-Post登陆请求

1、    案例:    两种方式的登录和请求参数提交

    网页版用户登录:jsp(客户端)+Servlet(服务器端)

    Android版用户登录:android(客户端)+Servlet(服务器端)
    
    网页版客户端用到的技术:
        网页发出Connection请求很简单,设定好请求路径后,由浏览器自动发出请求。只需指定method="GET/POST"。

    Android版客户端用到的技术:
        Android发出Connection请求需要手动发出。步骤如下,而且GET和POST不同。
        GET方式请求登录:
        
        1、准备请求路径和请求参数字符串
            String path = "http://192.168.1.10/login/LoginServlet?name=abc&password=123";
        由于浏览器会自动对中文的请求参数进行编码,如以下格式:%DE3%ADF,为了使服务器端接收到的数据
        不乱码,也需要对中文参数进行编码,格式如下:
            name = URLEncoder.encode(name);

        2、包装请求路径url
            URL url = new URL(path)

        3、创建请求连接对象
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        
        4、设置连接方式(并发出请求)和连接超时时长
            conn.setRequestMethod("GET");
            conn.setConnectionTimeout(5000);
        5、接收请求响应码和响应数据
            if(conn.getResponseCode==200){
                InputStream is = conn.getInputStream();
                byte [] data = StreamTools.getBytes(is);  
                /*StreamTools是一个工具类,将输入流中的数据存放到字节缓冲数组ByteArrayStream中,
                  这个数组的长度可以动太改变,因为如果直接用数组存,不知道要new 一个多大的数组,
                  直接声明的时候就给数组赋值,就不用指定数组的长度。
                */
                String result = new String(data);
            }

        POST方式请求登录:由于post方式是直接通过流的方式向服务器端写数据,所以步骤要多一些:
        1、设置请求路径字符串(不带请求参数)
            String path = "http://192.168.1.10/login/LoginServlet";

        2、包装请求 url
            URL url = new URL(path);
        
        3、创建连接
            HttpURLConnection conn = (HttpURLConnection)ur.openConnection();
        
        4、设置连接方式和连接超时时长
            conn.setRequestMethod("POST");
            conn.setConnectionTimeout(5000);
        
        5、准备好要发送的数据
            String data = "name="+URLEncoder.encode(name)+"password="+URLEncoder.encode(password);

        6、设置GET另外需要的请求头 Content-Type和Content-Length
            
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");            
            conn.setRequestProperty("Conent-Length",data.length()+"");

        7、告诉URLConnection是输入还是输出
            URL 连接可用于输入和/或输出。
            如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为                     
           false。默认值为 false;
            如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true; 如果不打算使用,则设置为                    
           false。默认值为 true。
            conn.setDoOutput(true);
        
        8、创建conn的输出流
            OutputStream os = conn.getOutputStream();
            
        9、输出内容
            os.write(data.getBytes());
        
        10、接收请求响应码和响应数据
            if(conn.getResponseCode==200){
                InputStream is = conn.getInputStream();
                byte [] data = StreamTools.getBytes(is);  
                /*StreamTools是一个工具类,将输入流中的数据存放到字节缓冲数组ByteArrayStream中,
                  这个数组的长度可以动太改变,因为如果直接用数组存,不知道要new 一个多大的数组,
                  直接声明的时候就给数组赋值,就不用指定数组的长度。
                */
                String result = new String(data);
            }
         <!################################################################################################!>

        HttpClient方式:相当于模拟浏览器的访问过程。
                1、打开一个浏览器
                2、准备数据
                3、敲回车,发出请求,接收响应。
         HttpGet方式登录:
            
            1、打开浏览器(创建HttpClient)
                HttpClient client = new DefaultHttpClient();
            
            2、准备好数据,并创建一个Get请求地址栏
                String name = URLEncoder.encode(name);
                String path = "http://192.168.1.10/login/LoginSevlet?name="+name+"password="+password;
                HttpGet httpGet = new HttpGet(path);
        
            3、敲回车,发出请求,接收响应。
                HttpResponse response = client.execute(httpGet);
                int code = response.getStatusLine().getStatusCode();
                if(code == 200){
                    InputStream is = response.getEntity().getContent();
                    String result = new String(StreamTools.getBytes(is));
                }
                
        HttpPost方式登录: (模拟)
            1、打开浏览器
                HttpClient client = new DefaultHttpClient();
                
            2、准备好数据,并创建一个Post请求地址栏
                String path ="http://192.168.1.10/login/LoginServlet";  //请求地址
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();  //请求数据(代替了输出流)
                parameters.add(new BasicNameValuePair("name",name);
                parameters.add(new BasicNameValuePair("password",password);
                
                httpPost = new httpPost(path);
                httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8");
            
            3、敲回车,发出请求,接收响应
                HttpResponse response = client.execute(httpPost);
                int code response.getStatusLine().getStatusCode();
                if(code == 200){
                    InputStream is = response.getEntity().getContent();
                    String result = new String(StreamTools.getBytes(is));
                }

             

示例:

使用HttpGet和HttpPost访问HTTP资源  

需求:用户登录(name:用户名,pwd:密码)

(一)HttpGet :doGet()方法
//doGet():将参数的键值对附加在url后面来传递
        public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{
                //服务器  :服务器项目  :servlet名称
                String path="http://192.168.5.21:8080/test/test";
                String uri=path+"?name="+name+"&pwd="+pwd;
                //name:服务器端的用户名,pwd:服务器端的密码
                //注意字符串连接时不能带空格
               
                String result="";
               
                HttpGet httpGet=new HttpGet(uri);
                HttpResponse response=new DefaultHttpClient().execute(httpGet);
                if(response.getStatusLine().getStatusCode()==200){
                        HttpEntity entity=response.getEntity();
                        result=EntityUtils.toString(entity, HTTP.UTF_8);
                }
                return result;
        }

(二)HttpPost :doPost()方法
//doPost():将参数打包到http报头中传递
        public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{
                //服务器  :服务器项目  :servlet名称
                String path="http://192.168.5.21:8080/test/test";
                HttpPost httpPost=new HttpPost(path);
                List<NameValuePair>list=new ArrayList<NameValuePair>();
                list.add(new BasicNameValuePair("name", name));
                list.add(new BasicNameValuePair("pwd", pwd));
                httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
               
                String result="";
               
                HttpResponse response=new DefaultHttpClient().execute(httpPost);
                if(response.getStatusLine().getStatusCode()==200){
                        HttpEntity entity=response.getEntity();
                        result=EntityUtils.toString(entity, HTTP.UTF_8);
                }
                return result;
        }


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值