AsyncHttpClient 开源框架學習研究
来源:互联网 发布:手机酷狗音乐数据异常 编辑:程序博客网 时间:2024/05/22 03:20
转载请注明出处:http://blog.csdn.net/krislight
OverView:
AsyncHttpClient庫 基於Apache的HttpClient框架,是一個異步的httpClient, 所有的http請求都在子線程中,但是callback執行的線程和創建這個callback的線程是同一個(也即主線程創建的callback那麼執行的時候也是在主線程中)
基本用法:
- AsyncHttpClient client = new AsyncHttpClient();
- client.get("http://www.google.com", new AsyncHttpResponseHandler() {
- @Override
- public void onStart() {
- super.onStart();
- //in MainThread, you can do some ui operation here like progressBar.
- }
- @Override
- public void onFinish() {
- // no matter success or failed this method is always invoke
- super.onFinish();
- }
- @Override
- public void onSuccess(String content) {
- //success
- }
- @Override
- public void onFailure(Throwable error, String content) {
- //failed
- }
- });
項目中建議定義成靜態工具類:
- public class TwitterRestClient {
- private static final String BASE_URL = "http://api.twitter.com/1/";
- private static AsyncHttpClient client = new AsyncHttpClient();
- public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
- client.get(getAbsoluteUrl(url), params, responseHandler);
- }
- public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
- client.post(getAbsoluteUrl(url), params, responseHandler);
- }
- private static String getAbsoluteUrl(String relativeUrl) {
- return BASE_URL + relativeUrl;
- }
- }
使用的时候:
- class TwitterRestClientUsage {
- public void getPublicTimeline() throws JSONException {
- TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
- @Override
- public void onSuccess(JSONArray timeline) {
- // Pull out the first event on the public timeline
- JSONObject firstEvent = timeline.get(0);
- String tweetText = firstEvent.getString("text");
- // Do something with the response
- System.out.println(tweetText);
- }
- });
- }
- }
保存Server端發送的Cookie:
- AsyncHttpClient myClient = new AsyncHttpClient();
- PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
- myClient.setCookieStore(myCookieStore);
如果想加入自己的Cookie:
- BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
- newCookie.setVersion(1);
- newCookie.setDomain("mydomain.com");
- newCookie.setPath("/");
- myCookieStore.addCookie(newCookie);
帶參數的Http請求:
可以這樣構造參數:- RequestParams params = new RequestParams();
- params.put("key", "value");
- params.put("more", "data");
也可以構造單個參數:
- RequestParams params = new RequestParams("single", "value");
還可以根據Map構造:
- HashMap<String, String> paramMap = new HashMap<String, String>();
- paramMap.put("key", "value");
- RequestParams params = new RequestParams(paramMap);
使用參數上傳文件:
1.傳入InputStream:
- InputStream myInputStream = blah;
- RequestParams params = new RequestParams();
- params.put("secret_passwords", myInputStream, "passwords.txt");
2.傳入File:
- File myFile = new File("/path/to/file.png");
- RequestParams params = new RequestParams();
- try {
- params.put("profile_picture", myFile);
- } catch(FileNotFoundException e) {}
3.傳入Byte數組:
- byte[] myByteArray = blah;
- RequestParams params = new RequestParams();
- params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
下載二進制形式的數據(如圖片,文件等)使用BinaryHttpResponseHandler:
- AsyncHttpClient client = new AsyncHttpClient();
- String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
- client.get("http://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) {
- @Override
- public void onSuccess(byte[] fileData) {
- // Do something with the file
- }
- });
基本的http授權驗證:
- AsyncHttpClient client = new AsyncHttpClient();
- client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
- client.get("http://example.com");
使用https安全連接:
- AsyncHttpClient client = new AsyncHttpClient();
- SSLSocketFactory sf = createSSLSocketFactory();
- if(sf != null){
- client.setSSLSocketFactory(sf);
- }
- HttpProtocolParams.setUseExpectContinue(client.getHttpClient().getParams(), false);
- return client;
createSSLSocketFactory方法如下:
- public static SSLSocketFactory createSSLSocketFactory(){
- MySSLSocketFactory sf = null;
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- trustStore.load(null, null);
- sf = new MySSLSocketFactory(trustStore);
- sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return sf;
- }
其中MySSLSocketFactory定義
- public class MySSLSocketFactory extends SSLSocketFactory {
- SSLContext sslContext = SSLContext.getInstance("TLS");
- public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
- super(truststore);
- TrustManager tm = new X509TrustManager() {
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- };
- sslContext.init(null, new TrustManager[] { tm }, null);
- }
- @Override
- public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
- injectHostname(socket, host);
- return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
- }
- @Override
- public Socket createSocket() throws IOException {
- return sslContext.getSocketFactory().createSocket();
- }
- private void injectHostname(Socket socket, String host) {
- try {
- Field field = InetAddress.class.getDeclaredField("hostName");
- field.setAccessible(true);
- field.set(socket.getInetAddress(), host);
- } catch (Exception ignored) {
- }
- }
- }
0 0
- AsyncHttpClient 开源框架學習研究
- AsyncHttpClient 开源框架學習研究
- 开源框架 Asynchttpclient
- http请求开源框架: AsyncHttpClient
- 安卓AsyncHttpClient网络开源框架
- 开源框架AsyncHttpClient的使用
- Android开源框架之AsyncHttpClient
- Android开源框架AsyncHttpClient (android-async-http)使用
- Android 使用开源框架AsyncHttpClient上传文件到服务器
- Android开源框架AsyncHttpClient (android-async-http)使用
- Android开源框架--AsyncHttpClient (android-async-http)使用
- 引用开源框架通过AsyncHttpClient处理get/post请求
- 引用开源框架通过AsyncHttpClient进行文件上传
- 通过开源框架AsyncHttpClient获取Json数据
- 使用开源框架AsyncHttpClient进行Json的Post请求
- Android 使用开源框架AsyncHttpClient上传文件到服务器
- 开源的HttpClient框架-----AsyncHttpClient的使用
- Android使用开源框架实现文件的上传 asyncHttpClient
- 浅谈软件销售工作
- poj1258 Agri-Net(Prim)
- android开发中,apk文件安装到\system\app 的解决办法 仅限root机
- 『IOS』UIScrollView的滑动
- Visual hull
- AsyncHttpClient 开源框架學習研究
- 风微风无服务为改革
- 第十周项目八:M$pszi$y是嘛意思?(二)
- cocos2dx移植android平台
- Android中pendingIntent的深入理解
- SxsTrace工具使用方法 MSVCP100.dll
- hadoop eclipse 配置
- ら抜き言葉
- 1027. Colors in Mars (20)