HttpClient 登录访问网络资源

使用 URLConnection 或 HttpURLConection 可以实现访问网络资源的功能,但如果需要访问一些受保护的资源时(登录后才能访问),对应这种应用场景就需要用到 HttpClient

 

Get 请求基本步骤

 

1、DefaultHttpClient  client = new  DefaultHttpClient(),建立 HttpClient()。由于 HttpClient() 是一个接口,所以在创建时,只能选择它的实现类 DefaultHttpClient 或 AndroidHttpClient。 

2、HttpGet  get = new HttpGet(String, url),发起 Get 请求的类。 Get 请求的参数可以直接连接在 URL 后面,也可以通过方法 setParams(HttpParams params) 实现。

3、HttpResponse respoonse = client.execute(get),请求后的响应对象,可以通过该对象获取服务器响应的信息。此处 execute(HttpUriRequest request) 的参数是 HttpUriRequest 类型,HttpGet 和 HttpPost 都实现了该接口。

4、int code = respnonse.getStatusLine().getStatusCode(),获取服务器返回的响应代码。实际上 getStatusLine() 方法会返回 StatusLine 对象,通过该对象的方法可以查看协议版本,响应代码等,常用的就是查看响应代码。HttpResponse 对象还提供了 getAllHeaders() 和 getHeader(String name) 这样的方法用于查询头部信息。

5、InputStream in = response.getEntity().getContent(),获取返回内容。方法 getEntity() 会返回 HttpEntity() 对象,该对象封装了服务器的响应内容。通过 HttpEntity 类的 getContent() 方法可以获取 InputStream,读取返回的内容。

 

Post 请求基本步骤

 

1、DefaultHttpClient  client = new  DefaultHttpClient(),创建 HttpClient() 对象。

2、BasicNameValuePair  pair = new  BasicNameValuePair(String name, String value),创建键值时,可以是请求的头部信息,也可以是请求的参数。由于一次请求的参数对有多个,因此这些对象应该添加到一个集合中。

3、 UrlEncodedFormEntity  entity = new  UrlEncodedFormEntity(List<NameVluePair>list, String encoding),创建 HttpEntity 实体,UrlEncodedFormEntity 实现了 HttpEntity 接口,在创建时可以指定编码格式。

4、HttpPost  post = new  HttpPost(String url),创建 HttpPost,此处 url 不包括请求串信息。

5、post.setEntity(entity),设置请求参数。

6、HttpResponse  response = client.execute(post),执行 Post 请求,得到 HttpResponse 对象。后面的处理过程与 Get 方式一致。

7、int code = response.getStatusLine().getStatusCode(),获取相应代码。

8、InputStream in = response.getEntity().getConten(),读取服务器返回的数据。

 

Android 客户端模拟登录系统

  1 import java.io.BufferedReader;
  2 import java.io.IOException;
  3 import java.io.InputStreamReader;
  4 import java.io.UnsupportedEncodingException;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import org.apache.http.HttpEntity;
  9 import org.apache.http.HttpResponse;
 10 import org.apache.http.NameValuePair;
 11 import org.apache.http.client.ClientProtocolException;
 12 import org.apache.http.client.HttpClient;
 13 import org.apache.http.client.entity.UrlEncodedFormEntity;
 14 import org.apache.http.client.methods.HttpGet;
 15 import org.apache.http.client.methods.HttpPost;
 16 import org.apache.http.impl.client.DefaultHttpClient;
 17 import org.apache.http.message.BasicNameValuePair;
 18 import org.apache.http.protocol.HTTP;
 19 import org.apache.http.util.EntityUtils;
 20 
 21 import android.os.Bundle;
 22 import android.os.Handler;
 23 import android.os.Message;
 24 import android.app.Activity;
 25 import android.app.AlertDialog.Builder;
 26 import android.content.DialogInterface;
 27 import android.util.Log;
 28 import android.view.LayoutInflater;
 29 import android.view.Menu;
 30 import android.view.View;
 31 import android.view.View.OnClickListener;
 32 import android.widget.Button;
 33 import android.widget.EditText;
 34 import android.widget.TextView;
 35 
 36 public class MainActivity extends Activity implements OnClickListener{
 37     
 38     Button b1,b2;
 39     TextView tv;
 40     HttpClient httpClient;
 41     
 42     Handler handler = new Handler(){
 43         @Override
 44         public void handleMessage(Message msg) {
 45             super.handleMessage(msg);
 46             
 47             tv.append(msg.obj.toString()+"\n");
 48         }
 49     };
 50     
 51     @Override
 52     protected void onCreate(Bundle savedInstanceState) {
 53         super.onCreate(savedInstanceState);
 54         
 55         setContentView(R.layout.activity_main);
 56         b1 = (Button) findViewById(R.id.bt_login);
 57         b2 = (Button) findViewById(R.id.bt_show);
 58         tv = (TextView) findViewById(R.id.tv);
 59         b1.setOnClickListener(this);
 60         b2.setOnClickListener(this);
 61         
 62         // 1、创建 HttpClient
 63         httpClient = new DefaultHttpClient();        
 64     }
 65     
 66     @Override
 67     public void onClick(View v) {
 68         
 69         if(v.getId() == R.id.bt_login){
 70             login();
 71         }else if(v.getId()== R.id.bt_show){
 72             showEmployee();
 73         }
 74     }
 75     
 76     // 系统登录,即访问 http://192.168.0.10:8080/part10_4_4/servlet/LoginServlet
 77     public void login(){
 78         
 79         // 使用自定义对话框登录
 80         final View loginView = LayoutInflater.from(this).inflate(R.layout.loginlayout, null);
 81         
 82         Builder builder = new Builder(this);
 83         builder.setTitle("系统登录")
 84         .setView(loginView)
 85         .setPositiveButton("登录", new DialogInterface.OnClickListener() {
 86             
 87             @Override
 88             public void onClick(DialogInterface dialog, int which) {
 89                 final String ln = ((EditText)loginView.findViewById(R.id.login_name)).getText().toString();
 90                 final String lp = ((EditText)loginView.findViewById(R.id.login_pwd)).getText().toString();
 91                 
 92                 // 开启线程登录
 93                 new Thread(new Runnable(){
 94                     @Override
 95                     public void run() {
 96                         String urlStr = "http://192.168.1.103:8080/part10_4_4/servlet/LoginServlet";
 97                         
 98                         // 2、创建键值对请求参数
 99                         List<NameValuePair> params = new ArrayList<NameValuePair>();
100                         params.add(new BasicNameValuePair("loginName",ln));
101                         params.add(new BasicNameValuePair("loginPwd",lp));
102                         try {
103                             // 3、创建实体对象
104                             HttpEntity entity = new UrlEncodedFormEntity(params,HTTP.UTF_8);
105                             // 4、创建 HttpPost对象
106                             HttpPost post = new HttpPost(urlStr);
107                             // 5、设置请求参数
108                             post.setEntity(entity);
109                             // 6、获取 HttpResponse 对象
110                             HttpResponse httpResponse = httpClient.execute(post);
111                             // 7、获取返回信息
112                             int code = httpResponse.getStatusLine().getStatusCode();
113                             Log.i("Tag", "服务器返回代码 " + code);
114                             String msg;
115                             if(code == 200){
116                                 // 8、读取数据, EntityUtils 是工具类,可以读取 Entity 中字符串内容
117                                 msg = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
118                             }else{
119                                 msg = "访问服务器错误!";
120                             }
121                             // Handler 通知主 UI 更新
122                             Message message = new Message();
123                             message.obj = msg;
124                             handler.sendMessage(message);
125                         } catch (UnsupportedEncodingException e) {
126                             // TODO Auto-generated catch block
127                             e.printStackTrace();
128                         } catch (ClientProtocolException e) {
129                             // TODO Auto-generated catch block
130                             e.printStackTrace();
131                         } catch (IOException e) {
132                             // TODO Auto-generated catch block
133                             e.printStackTrace();
134                         }
135                     }
136                 }).start();
137             }
138         })
139         .setNegativeButton("取消", new DialogInterface.OnClickListener() {
140             @Override
141             public void onClick(DialogInterface dialog, int which) {
142                 
143             }
144         }).show();
145     }
146     
147     // 查看受保护的资源,即访问 http://192.168.0.10:8080/part10_4_4/servlet/EmployeeServlet
148     // 如果没有登录,Session 中无登录信息,将无法查看
149     public void showEmployee(){
150         
151         new Thread(new Runnable(){
152             @Override
153             public void run() {
154                 String urlStr = "http://192.168.1.103:8080/part10_4_4/servlet/EmployeeServlet";
155                 // 2、创建 HttpGet
156                 HttpGet httpGet = new HttpGet(urlStr);
157                 BufferedReader br = null;
158                 try {
159                     // 3、获取 HttpResponse 对象
160                     HttpResponse httpResponse = httpClient.execute(httpGet);
161                     // 4、查看信息
162                     int code = httpResponse.getStatusLine().getStatusCode();
163                     Log.i("Tag", "服务器返回代码 " + code);
164                     String msg;
165                     if(code == 200){
166                         // 5、读取数据
167                         HttpEntity entity = httpResponse.getEntity();
168                         br = new BufferedReader(new InputStreamReader(entity.getContent()));
169                         msg = br.readLine();
170                     }else{
171                         msg = "访问服务器错误!";
172                     }
173                     // Handler 通知主 UI 更新
174                     Message message = new Message();
175                     message.obj = msg;
176                     handler.sendMessage(message);
177                 } catch (ClientProtocolException e) {
178                     // TODO Auto-generated catch block
179                     e.printStackTrace();
180                 } catch (IOException e) {
181                     // TODO Auto-generated catch block
182                     e.printStackTrace();
183                 }finally{
184                     if(br != null)
185                         try {
186                             br.close();
187                         } catch (IOException e) {
188                             // TODO Auto-generated catch block
189                             e.printStackTrace();
190                         }
191                 }
192             }
193         }).start();
194     }
195 }
MainActivity

布局文件

 1 <RelativeLayout 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     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context=".MainActivity" >
10     <LinearLayout 
11         android:layout_width="fill_parent"
12         android:layout_height="wrap_content"
13         android:id="@+id/layout"
14         android:orientation="horizontal"
15         android:gravity="center_horizontal"
16         >
17         <Button 
18             android:layout_width="wrap_content"
19             android:layout_height="wrap_content"
20             android:id="@+id/bt_login"
21             android:text="登录系统"
22             />
23         <Button 
24             android:layout_width="wrap_content"
25             android:layout_height="wrap_content"
26             android:id="@+id/bt_show"
27             android:text="查看员工"
28             />
29     </LinearLayout>
30     <TextView
31         android:layout_width="wrap_content"
32         android:layout_height="wrap_content"
33         android:layout_below="@id/layout"
34         android:id="@+id/tv" />
35 
36 </RelativeLayout>
activity_main.xml

添加权限

<uses-permission android:name="android.permission.INTERNET"/>

 

服务端是一个 MyEclispse Web 项目,主要有两个 Servlet,Run As MyEclipse Server Application。LoginServlet 用于登录,登录成功后会在 Session 中加入登录信息;

 1 import java.io.IOException;
 2 import java.io.PrintWriter;
 3 
 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 LoginServlet extends HttpServlet {
10 
11     /**
12      * The doGet method of the servlet. <br>
13      *
14      * This method is called when a form has its tag value method equals to get.
15      * 
16      * @param request the request send by the client to the server
17      * @param response the response send by the server to the client
18      * @throws ServletException if an error occurred
19      * @throws IOException if an error occurred
20      */
21     public void doGet(HttpServletRequest request, HttpServletResponse response)
22             throws ServletException, IOException {
23         
24         response.setCharacterEncoding("UTF-8");
25         String ln = request.getParameter("loginName");
26         String lp = request.getParameter("loginPwd");
27         System.out.println("服务器端,doPost执行。登录名:密码-->" + ln + ":" + lp);
28 
29         response.setContentType("text/html");
30         PrintWriter out = response.getWriter();
31         out.println("服务器端,doGet执行。登录名:密码-->" + ln + ":" + lp);
32         out.flush();
33         out.close();
34     }
35 
36     /**
37      * The doPost method of the servlet. <br>
38      *
39      * This method is called when a form has its tag value method equals to post.
40      * 
41      * @param request the request send by the client to the server
42      * @param response the response send by the server to the client
43      * @throws ServletException if an error occurred
44      * @throws IOException if an error occurred
45      */
46     public void doPost(HttpServletRequest request, HttpServletResponse response)
47             throws ServletException, IOException {
48         
49         response.setCharacterEncoding("UTF-8");
50         String ln=request.getParameter("loginName");
51         String lp=request.getParameter("loginPwd");
52         System.out.println("服务器端,doPost执行。登录名:密码-->" + ln + ":" + lp);
53         
54         response.setContentType("text/html");
55         PrintWriter out = response.getWriter();
56         out.println("服务器端,doPost执行。登录名:密码-->" + ln + ":" + lp);
57         out.flush();
58         out.close();
59     }
60 
61 }
LoginServlet.java

EmployeeServlet 通过判断 Session 中是否有登录信息响应不同的逻辑。

 1 import java.io.IOException;
 2 import java.io.PrintWriter;
 3 
 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 EmployeeServlet extends HttpServlet {
10 
11     /**
12      * The doGet method of the servlet. <br>
13      *
14      * This method is called when a form has its tag value method equals to get.
15      * 
16      * @param request the request send by the client to the server
17      * @param response the response send by the server to the client
18      * @throws ServletException if an error occurred
19      * @throws IOException if an error occurred
20      */
21     public void doGet(HttpServletRequest request, HttpServletResponse response)
22             throws ServletException, IOException {
23 
24         doPost(request, response);
25     }
26 
27     /**
28      * The doPost method of the servlet. <br>
29      *
30      * This method is called when a form has its tag value method equals to post.
31      * 
32      * @param request the request send by the client to the server
33      * @param response the response send by the server to the client
34      * @throws ServletException if an error occurred
35      * @throws IOException if an error occurred
36      */
37     public void doPost(HttpServletRequest request, HttpServletResponse response)
38             throws ServletException, IOException {
39         
40         response.setCharacterEncoding("UTF-8");
41         response.setContentType("text/html");
42         
43         String msg;
44         if(request.getSession().getAttribute("loginUser") != null){
45             msg = "欢迎 " + request.getSession().getAttribute("loginUser").toString() + " 登录!";
46         }else{
47             msg = "请先登录";
48         }
49         
50         PrintWriter out = response.getWriter();
51         out.println(msg);
52         out.flush();
53         out.close();
54     }
55 
56 }
EmployeeServlet.java

 

posted @ 2015-05-23 14:25  壬子木  阅读(334)  评论(0)    收藏  举报