zoukankan      html  css  js  c++  java
  • 012_01HttpClient用户登录

      HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

      

    使用 HttpClient 需要以下 6 个步骤:

    1. 创建 HttpClient 的实例

    2. 创建某种连接方法的实例,在这里是 GetMethod。在 GetMethod 的构造函数中传入待连接的地址

    3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例

    4. 读 response

    5. 释放连接。无论执行方法是否成功,都必须释放连接

    6. 对得到后的内容进行处理

    MainActivity.java

      1 package com.example.day12_01login;
      2 
      3 import java.io.InputStream;
      4 import java.net.URLEncoder;
      5 import java.util.ArrayList;
      6 import java.util.List;
      7 import org.apache.http.HttpEntity;
      8 import org.apache.http.HttpResponse;
      9 import org.apache.http.NameValuePair;
     10 import org.apache.http.client.HttpClient;
     11 import org.apache.http.client.entity.UrlEncodedFormEntity;
     12 import org.apache.http.client.methods.HttpGet;
     13 import org.apache.http.client.methods.HttpPost;
     14 import org.apache.http.impl.client.DefaultHttpClient;
     15 import org.apache.http.message.BasicNameValuePair;
     16 import com.cskaoyan.webutils.WebUtils;
     17 import android.app.Activity;
     18 import android.os.Bundle;
     19 import android.os.Handler;
     20 import android.os.Message;
     21 import android.view.View;
     22 import android.widget.EditText;
     23 import android.widget.Toast;
     24 
     25 public class MainActivity extends Activity {
     26 
     27     @Override
     28     protected void onCreate(Bundle savedInstanceState) {
     29         super.onCreate(savedInstanceState);
     30         setContentView(R.layout.activity_main);
     31     }
     32 
     33     Handler hanlder = new Handler(){
     34         @Override
     35         public void handleMessage(Message msg) {
     36             // TODO Auto-generated method stub
     37             super.handleMessage(msg);
     38             
     39             switch (msg.what) {
     40             case 1:
     41                 Toast.makeText(MainActivity.this, (String)msg.obj, 1).show();
     42                 break;
     43             case 2:
     44                 Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
     45                 break;
     46             default:
     47                 break;
     48             }
     49         }
     50     };
     51     
     52     
     53     //http client 的get请求
     54     public void login(View v){    
     55         EditText et_username = (EditText) findViewById(R.id.et_uername);
     56         EditText et_password = (EditText) findViewById(R.id.et_password);
     57         
     58         final String username= et_username.getText().toString();
     59         final String password= et_password.getText().toString();
     60         //http://localhost/LoginDemo/servlet/Login
     61         //发请求的线程
     62         Thread thread = new Thread(){
     63              public void run() {
     64                 String path = "http://192.168.3.30/LoginDemo/servlet/Login?username="+URLEncoder.encode(username)+"&password="+password;
     65                 HttpClient httpClient =null;
     66                 try {
     67                     
     68                      httpClient = new DefaultHttpClient();
     69                     HttpGet httpget= new HttpGet(path);
     70                     
     71                     HttpResponse httpResponse =httpClient.execute(httpget);
     72                     
     73                     //conn.getResponseCode()==200
     74                     if(httpResponse.getStatusLine().getStatusCode()==200){
     75                         InputStream  is=httpResponse.getEntity().getContent();                        
     76                         String text = WebUtils.gettextFromInputStream(is, null);
     77                         Message msg = hanlder.obtainMessage();
     78                         msg.what=1;
     79                         msg.obj=text;
     80                         hanlder.sendMessage(msg);    
     81                     }
     82                     else {            
     83                         Message msg = hanlder.obtainMessage();
     84                         msg.what=2;
     85                         msg.obj="连接服务器失败";
     86                         hanlder.sendMessage(msg);                        
     87                     }        
     88                 } catch (Exception e) {
     89                     // TODO Auto-generated catch block
     90                     e.printStackTrace();
     91                 }
     92                 finally{                    
     93                     if (httpClient!=null) {
     94                         httpClient.getConnectionManager().shutdown();     
     95                     }
     96                 }
     97                 
     98             };
     99         };
    100         thread.start();    
    101     }
    102     
    103     //http client Post 请求实现
    104     public void login2(View v){
    105         
    106         EditText et_username = (EditText) findViewById(R.id.et_uername);
    107         EditText et_password = (EditText) findViewById(R.id.et_password);
    108         
    109         final String username= et_username.getText().toString();
    110         final String password= et_password.getText().toString();
    111         
    112         //http://localhost/LoginDemo/servlet/Login
    113         //发请求的线程
    114         Thread thread = new Thread(){    
    115             public void run() {
    116                 String path = "http://192.168.3.39/LoginDemo/servlet/Login";
    117                      //data = username=%E7%8E%8B%E9%81%93&password=123456
    118                 String data = "username="+URLEncoder.encode(username)+"&password="+password;
    119                 HttpClient httpClient = null;
    120                 try {
    121                     httpClient = new DefaultHttpClient();
    122                     HttpPost   httpPost     = new HttpPost(path);
    123                     //HttpEntity httpEntity = new StringEntity(s);
    124                     List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    125                     
    126                     NameValuePair namevp= new BasicNameValuePair("username",username );                    
    127                     parameters.add(namevp);
    128                     NameValuePair namevp2= new BasicNameValuePair("password",password );
    129                     parameters.add(namevp2);
    130                     HttpEntity httpEntity = new  UrlEncodedFormEntity(parameters,"utf-8");
    131                     httpPost.setEntity(httpEntity);
    132                     
    133                     HttpResponse httpResponse =httpClient.execute(httpPost);
    134                     if(httpResponse.getStatusLine().getStatusCode()==200){                    
    135                         InputStream  is= httpResponse.getEntity().getContent();
    136                         String text = WebUtils.gettextFromInputStream(is, null);
    137                         is.close();
    138                         Message msg = hanlder.obtainMessage();
    139                         msg.what=1;
    140                         msg.obj=text;
    141                         hanlder.sendMessage(msg);    
    142                     }
    143                     else {            
    144                         Message msg = hanlder.obtainMessage();
    145                         msg.what=2;
    146                         msg.obj="连接服务器失败";
    147                         hanlder.sendMessage(msg);                        
    148                     }                
    149                 } catch (Exception e) {
    150                     // TODO Auto-generated catch block
    151                     e.printStackTrace();
    152                 }
    153                 finally{                    
    154                     if (httpClient!=null) {
    155                         httpClient.getConnectionManager().shutdown();     
    156                     }
    157                 }    
    158             };
    159         };
    160         thread.start();    
    161     } 
    162 }

    activity_main.xml

     1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     xmlns:tools="http://schemas.android.com/tools"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     tools:context="com.example.day12_01login.MainActivity"
     6     android:orientation="vertical" >
     7 
     8    
     9     <EditText
    10         android:id="@+id/et_uername"
    11         android:layout_width="fill_parent"
    12         android:layout_height="wrap_content" 
    13          />
    14     <EditText
    15         android:id="@+id/et_password"
    16         android:layout_width="fill_parent"
    17         android:layout_height="wrap_content" 
    18          />
    19     
    20     <RelativeLayout
    21          android:layout_width="fill_parent"
    22          android:layout_height="wrap_content" 
    23          >
    24         <CheckBox 
    25          android:id="@+id/cb_remeber"
    26          android:layout_width="wrap_content"
    27          android:layout_height="wrap_content" 
    28          android:layout_alignParentLeft="true"
    29         />
    30         <Button
    31         android:id="@+id/bt_login"      
    32         android:layout_width="wrap_content"
    33          android:layout_height="wrap_content"  
    34          android:layout_alignParentRight="true"
    35          android:onClick="login"
    36                   android:text="get login"
    37         />
    38         
    39     </RelativeLayout>
    40  
    41        <RelativeLayout
    42          android:layout_width="fill_parent"
    43          android:layout_height="wrap_content" 
    44          >
    45         <CheckBox 
    46          android:id="@+id/cb_remeber2"
    47          android:layout_width="wrap_content"
    48          android:layout_height="wrap_content" 
    49          android:layout_alignParentLeft="true"
    50         />
    51         <Button
    52         android:id="@+id/bt_login2"      
    53         android:layout_width="wrap_content"
    54          android:layout_height="wrap_content"  
    55          android:layout_alignParentRight="true"
    56          android:onClick="login2"
    57          android:text="post login"
    58         />
    59         
    60     </RelativeLayout>
    61 
    62          <Button
    63         android:id="@+id/bt_upload"      
    64         android:layout_width="wrap_content"
    65          android:layout_height="wrap_content"  
    66          android:layout_alignParentRight="true"
    67          android:onClick="upload"
    68                   android:text="uploadfile"
    69         />
    70 </LinearLayout>

    MyEclipse 创建的服务器端代码:

     1 package com.example.login;
     2 
     3 import java.io.IOException;
     4 import javax.servlet.ServletException;
     5 import javax.servlet.http.HttpServlet;
     6 import javax.servlet.http.HttpServletRequest;
     7 import javax.servlet.http.HttpServletResponse;
     8 
     9 public class Login extends HttpServlet {
    10     public void doGet(HttpServletRequest request, HttpServletResponse response)
    11             throws ServletException, IOException {
    12         request.setCharacterEncoding("utf-8");
    13         response.setContentType("text/html;charset=utf-8");
    14         String username = request.getParameter("username");
    15         String password = request.getParameter("password");
    16         
    17         if("woodrow".equals(username)&&"123456".equals(password))
    18         {
    19             response.getWriter().write("登陆成功");
    20         }
    21         else {
    22             response.getWriter().write("登陆失败");
    23         }
    24     }
    25 
    26     public void doPost(HttpServletRequest request, HttpServletResponse response)
    27             throws ServletException, IOException {
    28         this.doGet(request, response);
    29     }
    30 }
    物随心转,境由心造,一切烦恼皆由心生。
  • 相关阅读:
    57. Insert Interval
    56. Merge Intervals
    55. Jump Game
    54. Spiral Matrix
    52. N-Queens II
    More Effective C++ 条款2 最好使用C++转型操作符
    More Effective C++ 条款1 仔细区别pointers和references
    Python_内置函数之max
    python_超级基础
    python_format格式化输出、while else、逻辑运算符、编码初识
  • 原文地址:https://www.cnblogs.com/woodrow2015/p/4521542.html
Copyright © 2011-2022 走看看