AsyncHttpClient

AsyncHttpClient有个特性:
(11)持久化cookie存储,可以将cookie保存到你的应用程序的SharedPreferences中

AsyncHttpClient Cookie相关的官方的文档

This
library also includes a PersistentCookieStore which
is
an implementation of the Apache HttpClient CookieStore interface
that
automatically saves cookies to SharedPreferences storage
on
the Android device.

大概意思是将coolies自动保存到了首选项中。

写Cookie的场景

比如登录。在用户首次登录成功的时候,我们会从服务端取得Cookie,存储在用户手机的本地文件中。在用户下次打开应用时,会首先读取本地Cookie,Cookie没有过期的话,直接引导用户到相应界面,不再进行登录。

读Cookie的场景

除了登录之外,还有某些特殊的服务器请求,需要将本地Cookie信息一起发给服务端。

AsyncHttpClient会获取到你的cookies然后自动保存到你的首选项中,这时候只需要我们手动set一下即可,这样就保持了和服务端的session一致问题,也不会导致出现401权限错误,代码如下:

PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore); 

测试代码:

package com.example.cookietest;

import java.util.List;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.cookietest.LoginManager.ICallBack;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
//参考文章:http://blog.csdn.net/jdsjlzx/article/details/44632451

public class MainActivity extends Activity implements OnClickListener {
	private final String TAG = "MainActivity";
	//用户名
	EditText etUserName;
	// 密码
	EditText etPwd;
	// 登录按钮
	Button btnLogin;
	// 取消按钮
	Button btnCancel;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
		App app = (App) this.getApplication();
		app.mContext = getApplicationContext();

	}

	private void init() {
		etUserName = (EditText) findViewById(R.id.etUserName);
		etPwd = (EditText) findViewById(R.id.etPwd);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnLogin.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnLogin:
			/*new LoginManager().login(etUserName.getText().toString(), etPwd.getText().toString(), new ICallBack() {

				@Override
				public void onSuccess() {
					// TODO Auto-generated method stub
					Toast.makeText(App.mContext, "登录成功,cookie=" + Util.getPreference("cookie"), Toast.LENGTH_SHORT).show();
					startActivity(new Intent(MainActivity.this, GetVideoListActivity.class));
				}

				@Override
				public void onFailed(String error) {
					// TODO Auto-generated method stub
					Toast.makeText(App.mContext, error, Toast.LENGTH_SHORT).show();
				}
			});*/
			login(etUserName.getText().toString(), etPwd.getText().toString());
			break;

		case R.id.btnCancel:
			this.finish();
			break;
		default:
			break;
		}
	}

	private void login(String username, String password){
		String url = URLContainer.getLoginUrl(
				username, password);
		final AsyncHttpClient client = new AsyncHttpClient();

		//保存cookie,自动保存到了shareprefercece
		PersistentCookieStore myCookieStore = new PersistentCookieStore(MainActivity.this);
        client.setCookieStore(myCookieStore);

		client.post(url, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] errorResponse, Throwable e) {
				Log.e(TAG, "获取数据异常 ", e);
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] response) {
				String json = new String(response);
				Log.d(TAG, "onSuccess json = " + json);

				//测试获得已经保存的cookie
				Toast.makeText(App.mContext, "登录成功,cookie=" + getCookieText(), Toast.LENGTH_SHORT).show();
				startActivity(new Intent(MainActivity.this, GetVideoListActivity.class));
			}

		});

	}

	/**
	 * 获取标准 Cookie
	 */
	private String getCookieText() {
		PersistentCookieStore myCookieStore = new PersistentCookieStore(MainActivity.this);
		List<Cookie> cookies = myCookieStore.getCookies();
		Log.d(TAG, "cookies.size() = " + cookies.size());
		Util.setCookies(cookies);
		for (Cookie cookie : cookies) {
			Log.d(TAG, cookie.getName() + " = " + cookie.getValue());
		}
		 StringBuffer sb = new StringBuffer();
		for (int i = 0; i < cookies.size(); i++) {
			 Cookie cookie = cookies.get(i);
			 String cookieName = cookie.getName();
			 String cookieValue = cookie.getValue();
			if (!TextUtils.isEmpty(cookieName)
					&& !TextUtils.isEmpty(cookieValue)) {
				sb.append(cookieName + "=");
				sb.append(cookieValue + ";");
			}
		}
		Log.e("cookie", sb.toString());
		return sb.toString();
	}
}

代码下载:

http://download.csdn.net/detail/jdsjlzx/8541657

如有问题,请回复留言或者QQ:573842281

鉴于很多网友对怎么使用还是有疑问,这里再补充下。

自定义FinalAsyncHttpClient(注意:自定义是为了方便使用,每次从服务器请求数据都要带上cookie):

package com.lindo.collector.http;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;

import android.content.Context;

import com.lindo.collector.utils.MD5;
import com.lindo.collector.utils.Utils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;

public class FinalAsyncHttpClient {

	AsyncHttpClient client;

	public FinalAsyncHttpClient() {
		client = new AsyncHttpClient();
		client.setConnectTimeout(5);//5s超时
		if (Utils.getCookies() != null) {//每次请求都要带上cookie
			BasicCookieStore bcs = new BasicCookieStore();
			bcs.addCookies(Utils.getCookies().toArray(
					new Cookie[Utils.getCookies().size()]));
			client.setCookieStore(bcs);
		}
	}

	public AsyncHttpClient getAsyncHttpClient(){
		return this.client;
	}

}

请求数据:

private void getJoinedDoingsInfo(String id) {

		String url = Constant.USER_JOINED_TASK_INFO_URL;
		FinalAsyncHttpClient finalAsyncHttpClient = new FinalAsyncHttpClient();
		AsyncHttpClient client = finalAsyncHttpClient.getAsyncHttpClient();

		RequestParams params = new RequestParams();
		params.put("task_id", id);
		client.get(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {

			}

			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] data) {
				String json = new String(data);
				Log.d(TAG, "onSuccess " + json);

			}

		});
	}

Utils.java

public class Utils {

	private static List<Cookie> cookies;

	public static List<Cookie> getCookies() {
		return cookies != null ? cookies : new ArrayList<Cookie>();
	}

	public static void setCookies(List<Cookie> cookies) {
		Utils.cookies = cookies;
	}

}

登陆:

private void login(final String phoneNum, final String userPass) {
		Log.d(TAG, "login userPass = " + userPass);
		String url = Constant.USER_LOGIN_URL;
		FinalAsyncHttpClient finalAsyncHttpClient = new FinalAsyncHttpClient();
		AsyncHttpClient client = finalAsyncHttpClient.getAsyncHttpClient();

		saveCookie(client);

		RequestParams params = finalAsyncHttpClient.getCommonRequestParams(this);
		params.put("username", phoneNum);
		params.put("pwd", userPass);
		client.post(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] errorResponse, Throwable e) {

			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] response) {
				Log.d(TAG, "onSuccess statusCode = " + statusCode);
				String json = new String(response);
				Utils.setCookies(getCookie());}});}


在登陆时调用的方法

protected void saveCookie(AsyncHttpClient client) {
		PersistentCookieStore cookieStore = new PersistentCookieStore(this);
		client.setCookieStore(cookieStore);
	}

	protected List<Cookie> getCookie(){
		PersistentCookieStore cookieStore = new PersistentCookieStore(this);
		List<Cookie> cookies = cookieStore.getCookies();
		return cookies;
	}

	public void clearCookie(){
		PersistentCookieStore cookieStore = new PersistentCookieStore(this);
		cookieStore.clear();
	}

在Activity中调用:

private void getTaskPicTags(final String url){
		Log.d(TAG, "getTaskPicTags url = " + url);
		FinalAsyncHttpClient finalAsyncHttpClient = new FinalAsyncHttpClient();
		AsyncHttpClient client = finalAsyncHttpClient.getAsyncHttpClient();
		RequestParams params = finalAsyncHttpClient.getCommonRequestParams(this);
		client.get(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				String json = new String(responseBody);
				 Log.d(TAG, "onSuccess " + json);
				 			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				Log.e(TAG, "onFailure " , error);

			}
		});

	}

null

时间: 2024-10-05 07:29:04

AsyncHttpClient的相关文章

android-async-http AsyncHttpClient介绍

前一阵子刚搬了家,加上公司要发新版本,所以一直比较忙,文章也好几周没更新了.难得这个周末有空,正好周内偶然间闲逛 发现这个很不错的第三方开源类库,针对 Android开发中发送http请求的. 在Android开发中,发送.处理http请求简直太常见了,以至于我们的代码里到处充斥着各种HttpClient和与之相关又臭又长的代码, 它们存在于你代码的各个角落,每次看见都令人作呕,而你仅仅是为了server能返回一个string或者json给你.每次当我自己写这样 的代码时,我都会想能不能简化下这

Android网络请求框架AsyncHttpClient实例详解(配合JSON解析调用接口)

最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所帮助. 首先按照惯例先来简单了解一些AsyncHttpClient网络框架的一些知识. 1.简介 Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用android-a

第五章 服务熔断(hystrix)+ retrofit底层通信(AsyncHttpclient)

一.集群容错 技术选型:hystrix.(就是上图中熔断器) 熔断的作用: 第一个作用: 假设有两台服务器server1(假设可以处理的请求阈值是1W请求)和server2,在server1上注册了三个服务service1.service2.service3,在server2上注册了一个服务service4,假设service4服务响应缓慢,service1调用service4时,一直在等待响应,那么在高并发下,很快的server1处很快就会达到请求阈值(server1很快就会耗尽处理线程)之后

第二十八章 springboot + zipkin(brave定制-AsyncHttpClient)

brave本身没有对AsyncHttpClient提供类似于brave-okhttp的ClientRequestInterceptor和ClientResponseInterceptor,所以需要我们定制,而ServerRequestInterceptor和ServerResponseInterceptor是在BraveServletFilter部分直接指定就好了(这在任何client技术下都可以复用). 实际上,ClientRequestInterceptor和ClientResponseIn

开源项目(asyncHttpClient) get post 方式提交

get方式:   public static void requestNetForGetLogin(final Context context,final Handler handler ,final String username, final String password) {                 //使用HttpClient请求服务器将用户密码发送服务器验证                 try{                 String path = "http://

Android AsyncHttpClient

Android Asynchronous Http Client A Callback-Based Http Client Library for Android Tweet Downloadversion 1.4.2 (latest) or fork me on github Overview An asynchronous callback-based Http client for Android built on top of Apache's HttpClient libraries.

引用开源框架通过AsyncHttpClient进行文件上传

一.步骤: 1.添加权限(访问网络权限和读写权限) 2.获取上传文件路径并判断是否为空 3.若不为空,创建异步请求对象 4.创建上传文件路径 5.执行post请求(指定url路径,封装上传参数,新建AsyncHttpResponseHandler方法) 二.查看参考文档 三.实例项目解析 运行效果如下:       在本地文件夹中查看是否获取到图片,如下图显示 重点代码:均有详细解析,请认真查看注释 1.在AndroidManifest.xml中添加权限 <uses-permission and

异步网络加载开源框架AsyncHttpClient使用

AsyncHttpClient是异步的,但是有时候我们需要得到请求的结果集来返回给某个函数,由于是异步的,所以不能够直接return会去,所以可以定义一个interface来给调用AsyncHttpClient方法的一个回调来获取结果集,代码如下:定义回调接口: 点击(此处)折叠或打开 private static Callback mCallback; public interface Callback{ abstract void rankingsResultData(JSONArray r

AsyncHttpClient httpURLCon httpClient AsyncTask 访问服务器

Activity /**  * 测试使用三种方式(AsyncHttpClient.httpURLCon.httpClient)分别以get和post方式访问服务器  * @author 白乾涛  */ public class HttpComActivity extends ListActivity {     private TextView tv_result;     private ImageView imageView;     private String session_id;//

Asynchttpclient开源框架下载图片和文本,于Volley和Glide开源框架的区别。

AsyncHttpClient是一款比较流行的Android异步网路加载库,在github上的网址是:https://github.com/loopj/android-async-httpAsyncHttpClient和开源框架 Volley和Glide不同的是,不像Volley和Glide内部已经实现好了缓存策略,AsyncHttpClient自身没有实现缓存策略. 代码如下: 1 package com.lixu.asynchttpclient; 2 3 import org.apache.