`
bcyy
  • 浏览: 1829605 次
文章分类
社区版块
存档分类
最新评论

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();
			}
		});
	}
}


分享到:
评论

相关推荐

    httpclient-4.5所需jar包

    HTTP 协议可能是现在 Internet 上使用...HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.5 .6

    Android网络框架(Retrofit+Okhttp+Rxjava)、MVP模式(Dagger)

    可是在 Android 5.0 的时候 Google 就不推荐使用 HttpClient 了,到了 Android 6.0 (api 23) SDK,不再提供 org.apache.http.* (只保留几个类), 因此,设置 android SDK 的编译版本为23时,且使用了 httpClient 相关...

    Android中HttpURLConnection与HttpClient的使用与封装

     本文并不针对HTTP协议的具体内容,仅探讨android开发中使用HTTP协议访问网络的两种方式——HttpURLConnection和HttpClient  因为需要访问网络,需在AndroidManifest.xml中添加如下权限 &lt;uses android:name=...

    Android实验七.doc

    【实验要求】 1、 练习使用 HttpClient 建立网络连接,访问网络数据 2、 练习 XML 数据解析方法 3、 完成实验报告 二、实验内容 1、 电脑连接网络; 2、 新建 Android 应用程序项目 WeatherClient; 3、 业务逻辑代码...

    69.[开源][安卓][网络安全]NetCipher-master

    OnionKit是一个可以通过提供多种路径来提高移动应用网络安全的Android库项目。 该库具体提供: StrongTrustManager:TLS/SSL证书校验的一个强大实现,任何认证中心都可以进行定制; Proxied Connection Support...

    疯狂Android讲义源码

     第13章 Android的网络应用 476  13.1 基于TCP协议的网络通信 477  13.1.1 TCP协议基础 477  13.1.2 使用ServerSocket创建  TCP服务器端 478  13.1.3 使用Socket进行通信 479  13.1.4 加入多线程 483  13.2 ...

    Android开发案例驱动教程 配套代码

    15.2.3 Apache HttpClient实现方式 378 15.3 数据交换格式 380 15.3.1 纯文本格式 381 15.3.2 XML格式 381 15.3.3 JSON格式 385 15.4 自定义服务器端程序实例 387 15.4.1 Java Servlet概述 387 15.4.2 编写...

    Android开发的wifi网络测试小工具

    Android开发的测试网络连接质量的工具源码,分上传文件速度测试、下载文件速度测试和ping测试,有直观的界面查看测试过程,测试结果保存到文件。使用到了apache的HttpClient,和对ping命令的简单应用。

    Android ThinkAndroid开发框架.zip

    ThinkAndroid是一个免费的开源的、简易的、遵循Apache2开源协议发布的Android开发框架,其开发宗旨是简单、快速的进行 Android应用程序的开发,包含Android mvc、简易sqlite orm、ioc模块、封装Android httpclitent...

    疯狂Android讲义.part2

    第13章 Android的网络应用 476 13.1 基于TCP协议的网络通信 477 13.1.1 TCP协议基础 477 13.1.2 使用ServerSocket创建TCP 服务器端 478 13.1.3 使用Socket进行通信 479 13.1.4 加入多线程 483 13.2 使用URL访问网络...

    疯狂Android讲义.part1

    第13章 Android的网络应用 476 13.1 基于TCP协议的网络通信 477 13.1.1 TCP协议基础 477 13.1.2 使用ServerSocket创建TCP 服务器端 478 13.1.3 使用Socket进行通信 479 13.1.4 加入多线程 483 13.2 使用URL访问网络...

    微信支付源码appjava-All-Library-Android:使用库详细信息的所有android开发

    应用程序中执行任何类型的网络,它是在 OkHttp 网络层之上制作的 03 Android 异步网络和图像加载 04 用于 Java 的异步 Http 和 WebSocket 客户端库 05 适用于 Android 和 Java 应用程序的 HTTP 和 HTTP/2 客户端 06 ...

    微信支付源码appjava-android-library:精选的Android软件包和资源列表

    应用程序中执行任何类型的网络,它是在 OkHttp 网络层之上制作的 03 Android 异步网络和图像加载 04 用于 Java 的异步 Http 和 WebSocket 客户端库 05 适用于 Android 和 Java 应用程序的 HTTP 和 HTTP/2 客户端 06 ...

    java笔试题算法-awesome-android-libraries:精选的Android库精选列表

    应用程序中执行任何类型的网络,它是在 OkHttp 网络层之上制作的 03 Android 异步网络和图像加载 04 用于 Java 的异步 Http 和 WebSocket 客户端库 05 适用于 Android 和 Java 应用程序的 HTTP 和 HTTP/2 客户端 06 ...

    Volley-demo-master

    Android 提供了两个 HTTP 客户端AndroidHttpClient (扩展自 apache HTTPClient)和HttpUrlConnection来发出 HTTP 请求。 两者都有自己的优点和缺点。 在开发应用程序时,我们编写处理所有 HTTP 请求的 HTTP 连接类...

    android OnionKit

    OnionKit是一个可以通过提供多种路径来提高移动应用网络安全的Android库项目 改库具体提供:1、StrongTrustManager:TLS/SSL证书校验的一个强大实现,任何认证中心都可以进行定制 2、Proxied Connection Support:通过...

    Android项目源码ThinkAndroid开发框架.zip

    ThinkAndroid是一个免费的开源的、简易的、遵循Apache2开源协议发布的Android开发框架,其开发宗旨是简单、快速的进行 Android应用程序的开发,包含Android mvc、简易sqlite orm、ioc模块、封装Android httpclitent...

    Android静默安装常用工具类

    更详细的设置可以直接使用HttpURLConnection或apache的HttpClient。 源码可见HttpUtils.java,更多方法及更详细参数介绍可见HttpUtils Api Guide。 2、DownloadManagerPro Android系统下载管理DownloadManager增强...

    Andord和JAVA的HTTP&SPDY开源库

    源码okhttp,HTTP是现代网络...OKHTTP实现了类似于iava.net.HttpURLConnection API的核心模块,另外okhttp-apache模块实现了Apache Httpclient API。 OKHTTP支持Android2.2及以上版本,对于JAVA,则需要JAVA1.5以上。

Global site tag (gtag.js) - Google Analytics