android-async-http

工具类: 

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class HttpUtil {
    private static     AsyncHttpClient client =new AsyncHttpClient();    //实例话对象
    static
    {
        client.setTimeout(11000);   //设置链接超时,如果不设置,默认为10s
    }
     //不带参数  用一个完整url获取一个string对象
    public static void get(String urlString,AsyncHttpResponseHandler res)   
    {
        client.get(urlString, res);
    }
     //带参数 获取返回字符串
    public static void get(String urlString,RequestParams params,AsyncHttpResponseHandler res) // 
    {
        client.get(urlString, params,res);
    }
    //  不带参数,获取json对象或者数组
    public static void get(String urlString,JsonHttpResponseHandler res) //
    {
        client.get(urlString, res);
    }
     //带参数,获取json对象或者数组
    public static void get(String urlString,RequestParams params,JsonHttpResponseHandler res)  
    {
        client.get(urlString, params,res);
    }
    // 下载数据使用,会返回byte数据
    public static void get(String uString, BinaryHttpResponseHandler bHandler)  //
    {
        client.get(uString, bHandler);
    }
    //
    public static AsyncHttpClient getClient()
    {
        return client;
    }
}

利用以上工具的实例( get 请求 ): 

// 不带参数 ,返回String  (GET)
    public void method1(View view) {
        pDialog = ProgressDialog.show(this, "请稍等", "数据加载中");
        //一个菜谱的url地址
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10"; // 
        HttpUtil.get(urlString, new AsyncHttpResponseHandler() {
            public void onSuccess(String arg0) { // 获取数据成功会调用这里
                pDialog.dismiss();  //关闭
                textView.setText("获取json数据成功,看下面");
                textView2.setText(arg0);
                Log.i("hck", arg0);
            };
            public void onFailure(Throwable arg0) { // 失败,调用
                Toast.makeText(MainActivity.this, "onFailure",
                        Toast.LENGTH_LONG).show();
            };
            public void onFinish() { // 完成后调用,失败,成功,都要掉
            };
        });
    }
    
    // 带参数  返回的是JSONArray,
    public void method2(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?";
        RequestParams params = new RequestParams(); // 绑定参数
        params.put("type", "1");
        params.put("p", "2");
        params.put("size", "10");
        HttpUtil.get(urlString, params, new JsonHttpResponseHandler() {
            public void onSuccess(JSONArray arg0) { // 成功后返回一个JSONArray数据
                Log.i("hck", arg0.length() + "");
                try {
                    textView.setText("菜谱名字:"
                            + arg0.getJSONObject(2).getString("name")); //返回的是JSONArray, 获取JSONArray数据里面的第2个JSONObject对象,然后获取名字为name的数据值
                } catch (Exception e) {
                    Log.e("hck", e.toString());
                }
            };
            public void onFailure(Throwable arg0) {
                Log.e("hck", " onFailure" + arg0.toString());
            };
            public void onFinish() {
                Log.i("hck", "onFinish");
            };
            public void onSuccess(JSONObject arg0) {   //返回的是JSONObject,会调用这里
                Log.i("hck", "onSuccess ");
                try {
                    textView.setText("菜谱名字:"
                            + arg0.getJSONArray("list").getJSONObject(0)
                                    .getString("name"));
                } catch (Exception e) {
                    Log.e("hck", e.toString());
                }
            };
        });
    }
    //    不带参数  返回的是JSONObject,
    public void method3(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10";
        HttpUtil.get(urlString, new JsonHttpResponseHandler() {
            public void onSuccess(JSONObject arg0) {
                try {
                    textView.setText("菜谱名字:"
                            + arg0.getJSONArray("list").getJSONObject(1)
                                    .getString("name"));
                } catch (Exception e) {
                    Log.e("hck", e.toString());
                }
            };
        });
    }
    // 带参数 , 返回String
    public void method4(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?";
        final RequestParams params = new RequestParams();
        params.put("type", "1");
        params.put("p", "2");
        params.put("size", "10");
        HttpUtil.get(urlString, params, new AsyncHttpResponseHandler() {
            public void onSuccess(String arg0) {
                try {
                    JSONObject jObject = new JSONObject(arg0);
                    textView.setText("菜谱名字:"
                            + jObject.getJSONArray("list").getJSONObject(2)
                                    .getString("name"));
                    Log.i("hck", params.getEntity().toString());
                } catch (Exception e) {
                }
            };
        });
    }
    
 // 不带参数 下载图片 保存sd卡
    public void method5(View view) {
        String url = "http://f.hiphotos.baidu.com/album/w%3D2048/sign=38c43ff7902397ddd6799f046dbab3b7/9c16fdfaaf51f3dee973bf7495eef01f3b2979d8.jpg";
        HttpUtil.get(url, new BinaryHttpResponseHandler() {
            @Override
            public void onSuccess(byte[] arg0) {
                super.onSuccess(arg0);
                File file = Environment.getExternalStorageDirectory();
                File file2 = new File(file, "cat");
                file2.mkdir();
                file2 = new File(file2, "cat.jpg");
                try {
                    FileOutputStream oStream = new FileOutputStream(file2);
                    oStream.write(arg0);  //byte[] (arg0)  写入到 file2
                    oStream.flush();
                    oStream.close();
                    textView.setText("可爱的猫咪已经保存在sdcard里面");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("hck", e.toString());
                }
            }
        });
    }

其他: 

 // 有参数  post 上传文件
    public void uploadClick(View view){
        String path="http://10.0.2.2:8080/jsontest/servlet/UploadServlet";
        File myFile = new File("/sdcard/cat/cat.jpg");
        RequestParams params = new RequestParams();
        try {
            params.put("filename", myFile);
            
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(path, params, new AsyncHttpResponseHandler(){

                @Override
                public void onSuccess(int statusCode, String content) {
                    // TODO Auto-generated method stub
                    super.onSuccess(statusCode, content);
                    Toast.makeText(MainActivity.this, "上传成功!", Toast.LENGTH_LONG).show();
                }
                
                
            });
            
        } catch(FileNotFoundException e) {
            
        }
    }

//   有参数  post 上传图片 
        String path="http://sv1.livechano.com:8080/upload.action?&action=1.6&type=1&ext=png";
        File myFile = new File("/sdcard/test.png");
        RequestParams params = new RequestParams();
        try {
       //注意了,这种方法上传的参数一定要 设置params.put("image", myFile,"application/octet-stream");否则就会失败
            params.put("image", myFile,"application/octet-stream");
            AsyncHttpClient client = new AsyncHttpClient();
            
            client.post(path, params, new AsyncHttpResponseHandler(){
                
                @Override
                public void onFailure(Throwable error, String content) {
                    // TODO Auto-generated method stub
                    super.onFailure(error, content);
                    Toast.makeText(MainActivity.this, "上传失败!"+content, Toast.LENGTH_LONG).show();
                }
                
                @Override
                public void onSuccess(int statusCode, String content) {
                    // TODO Auto-generated method stub
                    super.onSuccess(statusCode, content);
                    System.out
                            .println("content:    "+content);
                    Toast.makeText(MainActivity.this, "上传成功!"+content, Toast.LENGTH_LONG).show();
                }
                
                
            });
            
        } catch(FileNotFoundException e) {
            
        }
    
    
// 带json参数的 post请求
try {  
            AsyncHttpClient client = new AsyncHttpClient();  
            JSONObject jsonObject = new JSONObject();  
            jsonObject.put("username", "ryantang");  
            StringEntity stringEntity = new StringEntity(jsonObject.toString());  
            client.post(MainActivity.this, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){  

                @Override  
                public void onSuccess(JSONObject jsonObject) {  
                    super.onSuccess(jsonObject);  
                      
                }  
                  
            });  
     } catch (JSONException e) {  
           e.printStackTrace();  
    } catch (UnsupportedEncodingException e) {  
          e.printStackTrace();  
    }  

附录:官方建议使用一个静态的AsyncHttpClient,像下面的这样 

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;
    }
}    

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。