一、自定义异步的HTTP请求

1.自定义一个AsyncHttpClient类,用于处理HTTP请求,实际原理就是新开启一个线程,调用HttpClient处理GET和POST请求

package com.shz.services;

import java.util.List;

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 android.os.Message; public class MyAsyncHttpClient { public void get(final String url,final MyHandler handler)
{
new Thread(){
public void run() {
Message msg = new Message();
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if(code == 200)
{
msg.what = 1;
msg.obj = loginService.readInputStream(response.getEntity().getContent());
}
else
{
msg.what = 2;
msg.obj = "请求失败,错误码:"+code;
} } catch (Exception e) {
msg.what = 2;
msg.obj = e.getMessage();
} finally{
handler.sendMessage(msg);
}
};
}.start();
} public void post(final String url,final List<NameValuePair> pairs,final MyHandler handler)
{
new Thread(){
public void run() {
Message msg = new Message();
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url); if(pairs != null)
{
post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
} HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if(code == 200)
{
msg.what = 1;
msg.obj = loginService.readInputStream(response.getEntity().getContent());
}
else
{
msg.what = 2;
msg.obj = "请求失败,错误码:"+code;
}
} catch (Exception e) {
msg.what = 2;
msg.obj = e.getMessage();
} finally{
handler.sendMessage(msg);
}
};
}.start();
}
}

2.处理服务器返回消息的MyHandler类,该类继承Handler

package com.shz.services;

import android.os.Handler;
import android.os.Message; public class MyHandler extends Handler {
public void onSuccess(String content) { } public void onFailure(String content) { } @Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
onSuccess(msg.obj.toString());
break;
case 2:
onFailure(msg.obj.toString());
break;
default:
break;
}
} }

3.测试代码

package com.shz.login;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List; import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair; import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast; import com.shz.myasynchttp.R;
import com.shz.services.MyAsyncHttpClient;
import com.shz.services.MyHandler; public class MainActivity extends Activity { private EditText txtUserName;
private EditText txtPassword; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); this.txtUserName = (EditText)this.findViewById(R.id.txtUserName);
this.txtPassword = (EditText)this.findViewById(R.id.txtPassword);
} public void loginGet(View view)
{
final String userName = this.txtUserName.getText().toString().trim();
final String password = this.txtPassword.getText().toString().trim(); if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
{
Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
return;
} String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
+ URLEncoder.encode(userName)
+ "&Password="
+ URLEncoder.encode(password); MyAsyncHttpClient client = new MyAsyncHttpClient();
client.get(path, new MyHandler(){ @Override
public void onSuccess(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} @Override
public void onFailure(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} });
} public void loginPost(View view)
{
final String userName = this.txtUserName.getText().toString().trim();
final String password = this.txtPassword.getText().toString().trim(); if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
{
Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
return;
} String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
MyAsyncHttpClient client = new MyAsyncHttpClient();
// 设置要提交的数据
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("UserName", userName));
pairs.add(new BasicNameValuePair("Password", password));
client.post(path, pairs, new MyHandler(){ @Override
public void onSuccess(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} @Override
public void onFailure(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} });
} }

布局代码

package com.shz.login;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List; import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair; import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast; import com.shz.myasynchttp.R;
import com.shz.services.MyAsyncHttpClient;
import com.shz.services.MyHandler; public class MainActivity extends Activity { private EditText txtUserName;
private EditText txtPassword; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); this.txtUserName = (EditText)this.findViewById(R.id.txtUserName);
this.txtPassword = (EditText)this.findViewById(R.id.txtPassword);
} public void loginGet(View view)
{
final String userName = this.txtUserName.getText().toString().trim();
final String password = this.txtPassword.getText().toString().trim(); if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
{
Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
return;
} String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
+ URLEncoder.encode(userName)
+ "&Password="
+ URLEncoder.encode(password); MyAsyncHttpClient client = new MyAsyncHttpClient();
client.get(path, new MyHandler(){ @Override
public void onSuccess(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} @Override
public void onFailure(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} });
} public void loginPost(View view)
{
final String userName = this.txtUserName.getText().toString().trim();
final String password = this.txtPassword.getText().toString().trim(); if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
{
Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
return;
} String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
MyAsyncHttpClient client = new MyAsyncHttpClient();
// 设置要提交的数据
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("UserName", userName));
pairs.add(new BasicNameValuePair("Password", password));
client.post(path, pairs, new MyHandler(){ @Override
public void onSuccess(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} @Override
public void onFailure(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
} });
} }

二、使用GitHub上的异步Http开源框架

loopj/android-async-http

示例代码

package com.shz.login;

import java.net.URLEncoder;

import org.apache.http.Header;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.shz.asynchttp.R; public class MainActivity extends Activity { private EditText txtUserName;
private EditText txtPassword;
private CheckBox cbRememberPwd; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); this.txtUserName = (EditText)this.findViewById(R.id.txtUserName);
this.txtPassword = (EditText)this.findViewById(R.id.txtPassword);
this.cbRememberPwd = (CheckBox)this.findViewById(R.id.cbRememberPwd); } public void loginGet(View view)
{
final String userName = this.txtUserName.getText().toString().trim();
final String password = this.txtPassword.getText().toString().trim(); if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
{
Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
return;
} String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
+ URLEncoder.encode(userName)
+ "&Password="
+ URLEncoder.encode(password); AsyncHttpClient client = new AsyncHttpClient();
client.get(path, new AsyncHttpResponseHandler() { @Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
} @Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
}
});
} public void loginPost(View view)
{
final String userName = this.txtUserName.getText().toString().trim();
final String password = this.txtPassword.getText().toString().trim(); if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
{
Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
return;
} String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
RequestParams params = new RequestParams();
params.put("UserName", userName);
params.put("Password", password);
AsyncHttpClient client = new AsyncHttpClient();
client.post(path, params, new AsyncHttpResponseHandler() { @Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
} @Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
}
});
} }

异步HTTP请求的更多相关文章

  1. iOS 多个异步网络请求全部返回后再执行具体逻辑的方法

    对于dispatch多个异步操作后的同步方法,以前只看过dispatch_group_async,看看这个方法的说明: * @discussion * Submits a block to a dis ...

  2. Android中的异步网络请求

    本篇文章我们来一起写一个最基本的Android异步网络请求框架,借此来了解下Android中网络请求的相关姿势.由于个人水平有限,文中难免存在疏忽和谬误,希望大家可以指出,谢谢大家:) 1. 同步网络 ...

  3. jmeter 异步子请求测试随笔

    好久没写技术类的博客了,都不知道自己都在忙啥.... 最近陆续遇到了一些异步子请求的测试需求,比如打开某一个页面A,A页面里的js会再调用B,C,D,E等请求,针对这个页面的测试,我最近做了一些思考: ...

  4. Java利用httpasyncclient进行异步HTTP请求

    Java利用httpasyncclient进行异步HTTP请求 前段时间有个需求在springmvc mapping的url跳转前完成一个统计的业务.显然需要进行异步的处理,不然出错或者异常会影响到后 ...

  5. jquery.ajax异步发送请求的简单测试

    使用ajax异步发送请求到一般处理程序,判断输入的用户名和密码 1.添加Html页面,导入jquery 2.编写js代码和页面标签 <script type="text/javascr ...

  6. JavaScript异步并发请求问题

    JavaScript异步并发请求问题 JS中如何处理多个ajax并发请求? jQuery的deferred对象详解 面试遇到的ajax请求串行和并行问题

  7. Android Asynchronous Http Client-Android异步网络请求客户端接口

    1.简介 Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用and ...

  8. AJAX其实就是一个异步网络请求

    AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML).其实就是一个异步网络请求. 一.创建对象 var xmlhttp; if (w ...

  9. IOS9中使用NSURLConection发送异步网络请求

    IOS9中使用NSURLConection发送异步网络请求 在ios9中,NSURLConection的sendSync..和sendAsync已经过时.被NSURLSession代替. 以下蓝色部分 ...

  10. 基于netty的异步http请求

    package com.pt.utils; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; im ...

随机推荐

  1. LtUpload上传组件

    <?php/** * The Upload class * @author Alex Lee <iuyes@qq.com> * @license http://opensource. ...

  2. Mongodb初学习--安装、试用

    MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案. 在MongoDB中数据被分组存储在数据集中,被称为一个集合(Collection ...

  3. 8.python中的数字

    python中数字对象的创建如下, a = 123 b = 1.23 c = 1+1j 可以直接输入数字,然后赋值给变量. 同样也可是使用类的方式: a = int(123) b = float(1. ...

  4. 推荐一个sqlce,sqllite等数据库管理工具

    推荐一个sqlce,sqllite等数据库管理工具 下载地址: http://fishcodelib.com/files/DatabaseNet4.zip 支持sqlserver,sqlce, sql ...

  5. 文件系统 第八次迭代 VFS相关说明

    麻烦访问evernote链接 http://www.evernote.com/shard/s133/sh/53e5b5ac-1192-4910-8bd5-6886218562af/59516c32a5 ...

  6. oracle自定义job名字,job调度

    一.调试创建 begin -- create_schedule dbms_scheduler.create_schedule(schedule_name => 's_change_send_da ...

  7. centos下各种c++库文件的安装

    Centos编译boost   1.下载最新的boost http://www.boost.org/   2.解压文件 tar -xzvf boost_1_45_0.tar.gz    3.编译bja ...

  8. HTML5七大优势“逼宫”APP

    HTML5颠覆了PC互联网的格局,优化了移动互联网的体验,接下来几年,HTML5将颠覆原生App世界. 跨平台: 在多屏年代,开发者的痛苦指数非常高,人人都期盼HTML5能扮演救星.多套代码.不同技术 ...

  9. IOS之表视图单元格删除、移动及插入

    1.实现单元格的删除,实现效果如下 - (void)viewDidLoad { [super viewDidLoad]; //设置导航栏 self.editButtonItem.title = @&q ...

  10. IOS 其他 - 如何让 app 支持32位和64位

    让App支持32-bit和64-bit基本步骤 1.确保Xcode版本号>=5.0.1 2.更新project settings, minimum deployment target >= ...