Android的网络应用-使用Apache HttpClient

Android的网络应用-使用Apache HttpClient

实例:访问被保护资源

创建项目:HttpClientTest

此项目要部署Web服务器,这里使用的Tomcat 7.0,在webApps目录下创建foo目录,并部署相应的文件

即foo/secret.jsp,foo/login.jsp

项目运行结果:

没有登录的情况下,访问被保护界面:

 

登陆系统:

 

 

登录成功后访问界面:

 

main.xml

<?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:id="@+id/get"
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content" 
	android:text="@string/get"
	/>
<Button  
	android:id="@+id/login"
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content" 
	android:text="@string/login"
	/>
</LinearLayout>
<EditText  
	android:id="@+id/response"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent"
	android:gravity="top" 
	android:editable="false"
	android:cursorVisible="false"
	/>
</LinearLayout>


 

login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <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="fill_parent"
        >
        <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>


 

package org.wwj.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.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
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 创建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://183.30.191.50: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;
						response.setText("");
						while ((line = br.readLine()) != null)
						{
							// 使用response文本框显示服务器响应
							response.append(line + "\n");
						}
					}
				}
				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.name)).getText()
									.toString();
								String pass = ((EditText) loginDialog
									.findViewById(R.id.pass)).getText()
									.toString();
								HttpPost post = new HttpPost(
										"http://183.30.191.50: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();
			}
		});
	}
}


 

posted on 2012-08-04 11:45  1.曲待续  阅读(393)  评论(0编辑  收藏  举报

导航