android-async-http库的使用

2016-06-05  本文已影响855人  JeremyDai

介绍

android中网络访问的第三方库github 地址:https://github.com/loopj/android-async-http
android-async-http主页:http://loopj.com/android-async-http/

特性

Gradle 中引用

在app的buid.gradle中添加
compile 'com.loopj.android:android-async-http:1.4.9'

使用

官方建议是通过静态类的方法来使用
twitter的例子
<pre> import com.loopj.android.http.*;
public class TwitterRestClient {
private static final String BASE_URL = "https://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; }}
</pre>

在client 端就可以这么用了

import org.json.*;import com.loopj.android.http.*;class TwitterRestClientUsage {    
public void getPublicTimeline() throws JSONException {        TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {           
 @Override           
 public void onSuccess(int statusCode, Header[] headers, JSONObject response) {              
  // If the response is JSONObject instead of expected JSONArray            }                     
   @Override        
    public void onSuccess(int statusCode, Header[] headers, 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);         
   }       
 });   
 }

传参:

RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
上一篇下一篇

猜你喜欢

热点阅读