android之访问被保护的资源

本文详细探讨了在Android环境中如何使用网络编程技术,特别是HttpClient,来访问和处理被保护的网络资源。通过实例讲解了设置请求头、授权认证等步骤,确保安全地访问受限制的数据。
摘要由CSDN通过智能技术生成
package org.crazyit.net;

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.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class HttpClientTest extends Activity
{
	TextView response;
	HttpClient httpClient;
	Handler handler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if(msg.what == 0x123)
			{
				// 使用response文本框显示服务器响应
				response.append(msg.obj.toString() + "\n");
			}
		}
	};
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 创建DefaultHttpClient对象
		httpClient = new DefaultHttpClient();
		response = (TextView) findViewById(R.id.response);
	}
	public void accessSecret(View v)
	{
		response.setText("");
		new Thread()
		{
			@Override
			public void run()
			{
				// 创建一个HttpGet对象
				HttpGet get = new HttpGet(
					"https://mail.qq.com/cgi-bin/loginpage");  //①
				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)
						{
							Message msg = new Message();
							msg.what = 0x123;
							msg.obj = line;
							handler.sendMessage(msg);
						}
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}.start();
	}
	public void showLogin(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)
				{
					// 获取用户输入的用户名、密码
					final String name = ((EditText) loginDialog
						.findViewById(R.id.name)).getText()
						.toString();
					final String pass = ((EditText) loginDialog
						.findViewById(R.id.pass)).getText()
						.toString();
					new Thread()
					{
						@Override
						public void run()
						{
							try
							{
								HttpPost post = new HttpPost("https://mail.qq.com/cgi-bin/loginpage");//③
								// 如果传递参数个数比较多的话可以对传递的参数进行封装
								List<NameValuePair> params = new
									ArrayList<NameValuePair>();
								params.add(new BasicNameValuePair
									("name", name));
								params.add(new BasicNameValuePair
									("pass", pass));								
								// 设置请求参数
								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());
									Looper.prepare();
									// 提示登录成功
									Toast.makeText(HttpClientTest.this,
										msg, Toast.LENGTH_SHORT).show();
									Looper.loop();
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
					}.start();
				}
			}).setNegativeButton("取消", null).show();
	}
}



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<LinearLayout
	android:orientation="horizontal"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:gravity="center_horizontal"
	>	
<Button  
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content" 
	android:text="@string/get"
	android:onClick="accessSecret"
	/>
<Button  
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content" 
	android:text="@string/login"
	android:onClick="showLogin"
	/>
</LinearLayout>
<TextView  
	android:id="@+id/response"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent"
	android:gravity="top" 
	android:background="#ffff"
	android:textColor="#f000"
	android:textSize="16dp"
	/>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<LinearLayout
	android:orientation="horizontal"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	>
<TextView  
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content"
	android:text="@string/name"
	/>
<EditText  
	android:id="@+id/name"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	/>
</LinearLayout>
<LinearLayout
	android:orientation="horizontal"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	>
<TextView  
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content"
	android:text="@string/pass"
	/>
<EditText  
	android:id="@+id/pass"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	/>
</LinearLayout>
</LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值