• 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;
        }
    }    
  • 相关阅读:
    [ACM_数学] 大菲波数 (hdu oj 1715 ,java 大数)
    [ACM_水题] 不要62(hdu oj 2089, 不含62和4的数字统计)
    [ACM_其他] Square Ice (poj1099 规律)
    [ACM_图论] Domino Effect (POJ1135 Dijkstra算法 SSSP 单源最短路算法 中等 模板)
    [ACM_搜索] Triangles(POJ1471,简单搜索,注意细节)
    [ACM_图论] Sorting Slides(挑选幻灯片,二分匹配,中等)
    [ACM_图论] The Perfect Stall 完美的牛栏(匈牙利算法、最大二分匹配)
    [ACM_几何] Metal Cutting(POJ1514)半平面割与全排暴力切割方案
    [ACM_动态规划] 轮廓线动态规划——铺放骨牌(状态压缩1)
    [ACM_数据结构] 竞赛排名
  • 原文地址:https://www.cnblogs.com/java-g/p/4136413.html
Copyright © 2020-2023  润新知