AsyncHttpClient
Posted Mr.xiaobai丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); } }); }
以上是关于AsyncHttpClient的主要内容,如果未能解决你的问题,请参考以下文章
android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件
HttpClient学习—— AsyncHttpClient使用