zoukankan      html  css  js  c++  java
  • 使用HttpClient访问被保护资源

    下面的Android应用需要向指定页面发送请求,但该页面并不是一个简单的页面,只有当用户已经登录,而且登录用户的用户名是crazyit.org时才可访问该页面。如果使用HTTPURLConnection来访问该页面,那么需要处理的细节就太复杂了。

    访问Web应用中被保护的页面,如果使用浏览器则十分简单,用户通过系统提供的登录页面登录系统,浏览器会负责维护与服务器之间的Session,如果用户登录的用户名、密码符合要求,就可以访问被保护资源了。

    为了通过HttpClient来访问被保护页面,程序同样需要使用HttpClient来登录系统,只要应用程序使用同一个HttpClient发送请求,HttpClient会自动维护与服务器之间的Session状态,也就是说程序第一次使用HttpClient登录系统后,接下来使用HttpClient即可访问被保护的页面了。

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;

    import android.os.Bundle;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class HttpClientTest extends Activity {
      Button get;
      Button login;
      EditText response;
      HttpClient httpClient;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_client_test);
        //创建DefaultHttpClient对象
        httpClient = new DefaultHttpClient();
        get = (Button) findViewById(R.id.get);
        login = (Button) findViewById(R.id.login);
        response = (EditText) findViewById(R.id.response);
        get.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {
            // 创建一个HttpGet对象
            HttpGet get = new HttpGet("http://172.18.5.198:8080/foo/secret.jsp");
            try {
              //发送GET请求
              HttpResponse httpResponse = httpClient.execute(get);
              HttpEntity entity = httpResponse.getEntity();
              if(entity != null){
                //读取服务器响应
                BufferedReader br = new BufferedReader(
                    new InputStreamReader(entity.getContent()));
                String line = null;
                while((line = br.readLine()) != null){
                  //使用response文本框显示服务器响应
                  response.append(line + " ");
                }
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        });
        login.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {
            final View loginDialog = getLayoutInflater()
                  .inflate(R.layout.login, null);
            new AlertDialog.Builder(HttpClientTest.this)
                  .setTitle("登录系统")
                  .setView(loginDialog)
                  .setPositiveButton("登录", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      String name = ((EditText)loginDialog.findViewById(
                              R.id.username)).getText().toString();
                      String pass = ((EditText)loginDialog.findViewById(
                              R.id.password)).getText().toString();
                      HttpPost post = new HttpPost("http://172.18.5.198:8080/foo/login.jsp");
                      //如果传递参数个数比较多可以对传递的参数进行封装
                      List<NameValuePair> params = new ArrayList<NameValuePair>();
                      params.add(new BasicNameValuePair("name", name));
                      params.add(new BasicNameValuePair("pass", pass));
                      try {
                        //设置请求参数
                        post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
                        //发送POST请求
                        HttpResponse response = httpClient.execute(post);
                        //如果服务器成功地返回响应
                        if(response.getStatusLine().getStatusCode() == 200){
                          String msg = EntityUtils.toString(response.getEntity());
                          //提示登陆成功
                          Toast.makeText(HttpClientTest.this, msg, 5000).show();
                        }
                      } catch (Exception e) {
                        e.printStackTrace();
                      }
                    }
                  }).setNegativeButton("取消", null).show();
            }
         });
      }

    }

    登陆成功后,HttpClient将会自动维护与服务器之间的连接,并维护与服务器之间的Session状态。

  • 相关阅读:
    3164 质因数分解
    codevs3249搭积木
    codevs 2964公共素数因数
    爱改名的小融1
    单链表基础练习
    并查集(union-find sets)
    string类中字符的大小写转换
    蒜头君学英语--set()练习
    打印锯齿矩阵
    堆积木
  • 原文地址:https://www.cnblogs.com/jiww/p/5641669.html
Copyright © 2011-2022 走看看