码迷,mamicode.com
首页 > Web开发 > 详细

AsyncHttpClient httpURLCon httpClient AsyncTask 访问服务器

时间:2016-06-04 19:21:19      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:


Activity
技术分享
/**
 * 测试使用三种方式(AsyncHttpClient、httpURLCon、httpClient)分别以get和post方式访问服务器
 * @author 白乾涛
 */
public class HttpComActivity extends ListActivity {
    private TextView tv_result;
    private ImageView imageView;
    private String session_id;//每次登录都不一样
    private int uid;//10415362
    private String picUrl;//每次登录都不一样
    /**拼接的URL地址*/
    private static String URL_HEAD = "http://" + AsyncXiuHttpHelper.SERVER_URL;
    public static final int GET_ASYNC_HTTP = 0;
    public static final int POST_ASYNC_HTTP = 1;
    public static final int GET_HTTP_URL_CON = 2;
    public static final int POST_HTTP_URL_CON = 3;
    public static final int GET_HTTP_CLIENT = 4;
    public static final int POST_HTTP_CLIENT = 5;
    public static final int LOAD_PIC_BY_HANDLER = 6;
    public static final int LOAD_PIC_BY_ASYNCTASK = 7;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        String[] array = { "使用AsyncHttpClient的get方式""使用AsyncHttpClient的post方式"//
                "使用httpURLCon的get方式""使用httpURLCon的post方式"//
                "使用httpClient的get方式""使用httpClient的post方式",//
                "使用httpURLCon+handler加载图片""使用httpURLCon+AsyncTask加载图片" };
        for (int i = 0; i < array.length; i++) {
            array[i] = i + "、" + array[i];
        }
        imageView = new ImageView(this);
        getListView().addFooterView(imageView);
        tv_result = new TextView(this);// 将内容显示在TextView中
        tv_result.setTextColor(Color.BLUE);
        tv_result.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_result.setPadding(20, 10, 20, 10);
        getListView().addFooterView(tv_result);
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1new ArrayList<String>(Arrays.asList(array))));
        //初始化
        if (MyApplication.getApplication().getUser() != null) {
            session_id = MyApplication.getApplication().getUser().getuSessionId();//设置完后就可以获取了
            uid = MyApplication.getApplication().getUser().getuId();
            tv_result.setText("session_id=" + session_id + "\n" + "uid=" + uid);
        } else tv_result.setText("请先登录再操作");
    }
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        picUrl = UrlOfPics.urls[new Random().nextInt(UrlOfPics.urls.length)];
        switch (position) {
        case GET_ASYNC_HTTP:
            asyncGetNotifaction();
            break;
        case POST_ASYNC_HTTP:
            asyncModifySignature();
            break;
        case GET_HTTP_URL_CON:
            httpURLConGet();
            break;
        case POST_HTTP_URL_CON:
            httpURLConPost();
            break;
        case GET_HTTP_CLIENT:
            httpClientGet();
            break;
        case POST_HTTP_CLIENT:
            httpClientPost();
            break;
        case LOAD_PIC_BY_HANDLER:
            loadPicByHandler();
            break;
        case LOAD_PIC_BY_ASYNCTASK:
            new MyImageLoadTask().execute(picUrl);
            break;
        }
    }
    //**************************************************************************************************************************
    //                                                                         使用异步框架AsyncHttpClient访问服务器
    //**************************************************************************************************************************
    /**
     * 获取活动通知数据,get
     */
    private void asyncGetNotifaction() {
        RequestParams params = new RequestParams();
        params.put("session_id"session_id);
        params.put("uid"uid);
        ProgressDialogUtil.showProgressDialog(HttpComActivity.this"""申请中...");
        AsyncXiuHttpHelper.get(UrlOfServer.RQ_NOTIFICATION, params, new OnHttpListener<JSONObject>() {
            @Override
            public void onHttpListener(boolean httpSuccessed, final JSONObject obj) {//运行UI线程中
                ProgressDialogUtil.dismissProgressDialog();
                tv_result.setText(JsonFormatTool.formatJson(obj.toString()));
                new Thread() {//子线程中请求网络
                    @Override
                    public void run() {
                        //final String img = obj.getJSONArray("news").getJSONObject(0).getString("img");
                        InputStream stream = HttpUrlClientUtils.getInputStreamFromUrl(picUrl);//这里使用另一张图片演示
                        final Bitmap bitmap = BitmapFactory.decodeStream(stream);
                        runOnUiThread(new Runnable() {//主线程总更新UI。如果数据比较复杂,应该用handler处理
                            @Override
                            public void run() {
                                imageView.setImageBitmap(bitmap);
                            }
                        });
                    }
                }.start();
            }
        });
    }
    /**
     * 提交用户个性签名,post
     */
    private void asyncModifySignature() {
        RequestParams params = new RequestParams();
        params.put("session_id"session_id);
        params.put("uid"uid);
        params.put("sig_data""签名内容:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
        ProgressDialogUtil.showProgressDialog(HttpComActivity.this"""申请中...");
        AsyncXiuHttpHelper.post(UrlOfServer.RQ_USER_SIGNATURE, params, new OnHttpListener<JSONObject>() {
            @Override
            public void onHttpListener(boolean httpSuccessed, JSONObject obj) {
                ProgressDialogUtil.dismissProgressDialog();
                tv_result.setText(JsonFormatTool.formatJson(obj.toString()));
                imageView.setImageResource(R.drawable.ic_launcher);
            }
        });
    }
    //**************************************************************************************************************************
    //                                                                             使用HttpURLConnection访问服务器
    //**************************************************************************************************************************
    /**
     * 使用java.net.HttpURLConnection类的【GET】的方式,获取活动通知数据
     */
    private void httpURLConGet() {
        ProgressDialogUtil.showProgressDialog(HttpComActivity.this"""申请中...");
        new Thread(new Runnable() {//子线程中请求网络
                    @Override
                    public void run() {
                        String parameters = "session_id=" + session_id + "&uid=" + uid;//请求参数
                        final String strJson = HttpUrlClientUtils.httpURLConGet(URL_HEAD + UrlOfServer.RQ_NOTIFICATION, parameters);
                        //final String img = new JSONObject(strJson).getJSONArray("news").getJSONObject(0).getString("img");
                        InputStream stream = HttpUrlClientUtils.getInputStreamFromUrl(picUrl);//这里使用另一张图片演示
                        final Bitmap bitmap = BitmapFactory.decodeStream(stream);
                        runOnUiThread(new Runnable() {//主线程中更新UI
                            @Override
                            public void run() {
                                ProgressDialogUtil.dismissProgressDialog();
                                tv_result.setText(JsonFormatTool.formatJson(strJson));
                                imageView.setImageBitmap(bitmap);
                            }
                        });
                    }
                }).start();
    }
    /**
     * 使用java.net.HttpURLConnection类的【POST】的方式,提交用户个性签名
     */
    private void httpURLConPost() {
        ProgressDialogUtil.showProgressDialog(HttpComActivity.this"""申请中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String sig_data = "签名内容:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
                String requestBody = "session_id=" + session_id + "&uid=" + uid + "&sig_data=" + sig_data;//请求体中的数据即为get请求URL路径?后面的内容
                final String str = HttpUrlClientUtils.httpURLConPost(URL_HEAD + UrlOfServer.RQ_USER_SIGNATURE, requestBody);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ProgressDialogUtil.dismissProgressDialog();
                        imageView.setImageResource(R.drawable.ic_launcher);
                        try {
                            tv_result.setText(JsonFormatTool.formatJson(new JSONObject(str).toString()));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }
    //**************************************************************************************************************************
    //                                                                                      使用HttpClient访问服务器
    //**************************************************************************************************************************
    /**
     * 使用org.apache.http.client.HttpClient的【Get】的方式登录
     */
    private void httpClientGet() {
        ProgressDialogUtil.showProgressDialog(HttpComActivity.this"""申请中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String parameters = "session_id=" + session_id + "&uid=" + uid;//请求参数
                final String strJson = HttpUrlClientUtils.httpClientGet(URL_HEAD + UrlOfServer.RQ_NOTIFICATION, parameters);
                //final String img = new JSONObject(strJson).getJSONArray("news").getJSONObject(0).getString("img");
                InputStream stream = HttpUrlClientUtils.getInputStreamFromUrl(picUrl);//这里使用另一张图片演示
                final Bitmap bitmap = BitmapFactory.decodeStream(stream);
                runOnUiThread(new Runnable() {//主线程中更新UI
                    @Override
                    public void run() {
                        ProgressDialogUtil.dismissProgressDialog();
                        tv_result.setText(JsonFormatTool.formatJson(strJson));
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }
    /**
     * 使用org.apache.http.client.HttpClient的【Post】的方式登录
     */
    private void httpClientPost() {
        ProgressDialogUtil.showProgressDialog(HttpComActivity.this"""申请中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String sig_data = "签名内容:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
                // 设置post请求的参数,代表发送给服务器的实体中的内容
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                parameters.add(new BasicNameValuePair("session_id"session_id));
                parameters.add(new BasicNameValuePair("uid"uid + ""));
                parameters.add(new BasicNameValuePair("sig_data", sig_data));
                //参数的类型为【HttpEntity】接口,其实现类UrlEncodedFormEntity中的元素为键值对形式的【BasicNameValuePair】对象
                final String str = HttpUrlClientUtils.httpClientPost(URL_HEAD + UrlOfServer.RQ_USER_SIGNATURE, parameters);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ProgressDialogUtil.dismissProgressDialog();
                        imageView.setImageResource(R.drawable.ic_launcher);
                        try {
                            tv_result.setText(JsonFormatTool.formatJson(new JSONObject(str).toString()));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }
    public static final int MSG_WHAT_BITMAP = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_WHAT_BITMAP:
                imageView.setImageBitmap((Bitmap) (msg.obj));
                break;
            }
        }
    };
    private void loadPicByHandler() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = HttpUrlClientUtils.getInputStreamFromUrl(picUrl);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                mHandler.sendMessage(Message.obtain(mHandlerMSG_WHAT_BITMAP, bitmap));
            }
        }).start();
    }
    class MyImageLoadTask extends AsyncTask<String, Bitmap, Bitmap> {
        protected Bitmap doInBackground(String... params) {
            InputStream inputStream = HttpUrlClientUtils.getInputStreamFromUrl(params[0]);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            imageView.setImageBitmap(result);
        }
    }
}

http访问服务器工具类
/** 
 * HttpURLConnection和HttpClient工具类
 * HttpURLConnection是java.net中的类,属于标准的java接口,在4.4版本的源码中被OkHttp替换掉了;HttpClient则是Apache提供的,已经被Google弃用了。
 * 一般我们实际开发中都是使用别人封装好的第三方网络请求框架,诸如:Volley,android-async-http,loopj等。
 * */
public class HttpUrlClientUtils {
    //*********************************************************************************************************************************************
    //                                                                                                                 HttpURLConnection
    //*********************************************************************************************************************************************
    /** 使用java.net.HttpURLConnection类的【GET】的方式登录     */
    public static String httpURLConGet(String strUrl, String parameters) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(strUrl + "?" + parameters);//"?"后面的内容都属于请求头中的内容,服务器获取到请求信息后通过"&"分离出数据
            httpURLConnection = (HttpURLConnection) url.openConnection();//打开指定URL的连接
            httpURLConnection.setRequestMethod("GET"); // get或者post必须大写
            httpURLConnection.setConnectTimeout(3000); // 连接的超时时间,非必须
            httpURLConnection.setReadTimeout(3000); // 读数据的超时时间,非必须
            httpURLConnection.setRequestProperty("User-Agent""Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");//非必须
            int responseCode = httpURLConnection.getResponseCode();//获取响应码
            if (responseCode == 200) {
                InputStream is = httpURLConnection.getInputStream();
                String result = getStringFromInputStream(is);
                return result;
            } else return "失败";
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "MalformedURLException";
        } catch (ProtocolException e) {
            e.printStackTrace();
            return "ProtocolException";
        } catch (IOException e) {
            e.printStackTrace();
            return "IOException";
        } finally {
            if (httpURLConnection != null) httpURLConnection.disconnect(); // 关闭连接
        }
    }
    /** 使用java.net.HttpURLConnection类的【POST】的方式登录     */
    public static String httpURLConPost(String strUrl, String requestBody) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(strUrl);//区别1,URL不同,POST仅包含路径,不包含?后面的内容
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true); // 必须设置此方法,默认情况下, 系统不允许向服务器输出内容
            httpURLConnection.setConnectTimeout(3000); // 连接的超时时间,非必须
            httpURLConnection.setReadTimeout(3000); // 读数据的超时时间,非必须
            httpURLConnection.setUseCaches(false);//Post方式不能缓存,非必须
            // 添加请求头,非必须
            httpURLConnection.setRequestProperty("User-Agent""Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");//浏览器
            httpURLConnection.setRequestProperty("Accept-Charset""utf-8");//编码
            httpURLConnection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");//数据类型
            //    httpURLConnection.setRequestProperty("Content-Length", requestBody.length() + "");//不知道为什么,设置此属性后会报ProtocolException!
            OutputStream out = httpURLConnection.getOutputStream();// 获得一个输出流, 用于向服务器写数据
            out.write(requestBody.getBytes());//采用的是平台默认的字符集编码UTF-8,请求体中的数据即为get请求URL路径?后面的内容    
            out.close();
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream is = httpURLConnection.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else return "失败";
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "MalformedURLException";
        } catch (ProtocolException e) {
            e.printStackTrace();
            return "ProtocolException";
        } catch (IOException e) {
            e.printStackTrace();
            return "IOException";
        } finally {
            if (httpURLConnection != null) httpURLConnection.disconnect();
        }
    }
    //*********************************************************************************************************************************************
    //                                                                                                                 HttpClient
    //*********************************************************************************************************************************************
    /** 使用org.apache.http.client.HttpClient的【Get】的方式登录     */
    public static String httpClientGet(String strUrl, String parameters) {
        HttpClient httpClient = null;
        try {
            httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(strUrl + "?" + parameters);
            HttpResponse response = httpClient.execute(httpGet); //HttpResponse对象中包含了服务器响应的全部信息
            int statusCode = response.getStatusLine().getStatusCode();// 获得服务器响应中的【响应行中的响应码】
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();//获取实体内容
                String text = getStringFromInputStream(is);
                return text;
            } else return "失败";
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return "IllegalStateException";
        } catch (IOException e) {
            e.printStackTrace();
            return "IOException";
        } finally {
            if (httpClient != null) httpClient.getConnectionManager().shutdown(); // 关闭连接, 释放资源
        }
    }
    /** 使用org.apache.http.client.HttpClient的【Post】的方式登录     */
    public static String httpClientPost(String strUrl, List<NameValuePair> parameters) {
        HttpClient httpClient = null;
        try {
            httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(strUrl);
            HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
            httpPost.setEntity(entity);//设置实体内容
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                InputStream is = response.getEntity().getContent();
                String text = getStringFromInputStream(is);
                return text;
            } else return "失败";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "UnsupportedEncodingException";
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return "ClientProtocolException";
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return "IllegalStateException";
        } catch (IOException e) {
            e.printStackTrace();
            return "IOException";
        } finally {
            if (httpClient != null) httpClient.getConnectionManager().shutdown(); // 关闭连接和释放资源
        }
    }
    //*********************************************************************************************************************************************
    //                                                                                                                  其他方法
    //*********************************************************************************************************************************************
    /**从流中读取数据,返回字节数组*/
    public static byte[] getBytesFromInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// 字节数组输出流(内存输出流):可以捕获内存缓冲区的数据,转换成字节数组
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**  将输入流转换成字符串信息 */
    public static String getStringFromInputStream(InputStream is) {
        byte[] bytes = getBytesFromInputStream(is);
        String temp = new String(bytes);//默认为UTF8编码
        if (temp.contains("utf-8")) return temp;
        else if (temp.contains("gb2312") || temp.contains("gbk")) {
            try {
                return new String(bytes, "gbk");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return temp;
    }
    /** 打开指定URL的URLConnection对象,获取一个InputStream */
    public static InputStream getInputStreamFromUrl(String url) {
        try {
            URLConnection conn = new URL(url).openConnection();
            conn.setConnectTimeout(3 * 1000);
            conn.setReadTimeout(3 * 1000);
            return conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

AsyncHttp封装
/**AsyncHttp访问网络的工具类*/
public class AsyncHttpHelper {
    public static final int HTTP_OK = 200;
    public static final String HTTP_ERROR = "系统繁忙,请稍后再试";
    //**************************************************************************************************************************
    //                                                                                                       最核心的两个方法
    //**************************************************************************************************************************
    /**
     * get 请求
     */
    public static void get(final String serverName, final String relativeUrl, RequestParams params, final OnHttpListener<JSONObject> onHttpListner) {
        if (params == null) params = new RequestParams();
        AsyncHttpClient asyncHttpClient = new com.loopj.android.http.AsyncHttpClient();
        asyncHttpClient.setTimeout(5000);
        try {
            String url = "http://" + serverName + relativeUrl;
            asyncHttpClient.get(url, params, new JsonHttpResponseHandler("UTF-8") {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    super.onFailure(statusCode, headers, responseString, throwable);
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    throwable.printStackTrace();
                    if (onHttpListner != null) onHttpListner.onHttpListener(falsegetErrorJson(HTTP_ERROR));
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    if (onHttpListner != null) {
                        if (statusCode == HTTP_OK) {
                            response = (response == null ? new JSONObject() : response);
                            onHttpListner.onHttpListener(true, response);
                        } else onHttpListner.onHttpListener(false, response);
                    }
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                    super.onSuccess(statusCode, headers, response);
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    super.onSuccess(statusCode, headers, responseString);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (onHttpListner != null) onHttpListner.onHttpListener(falsegetErrorJson(HTTP_ERROR));
        }
    }
    /**
     * post 请求
     */
    public static void post(final String serverName, final String relativeUrl, RequestParams params, final OnHttpListener<JSONObject> onHttpListner) {
        if (params == null) params = new RequestParams();
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.setTimeout(5000);
        try {
            String url = "http://" + serverName + relativeUrl;
            asyncHttpClient.post(url, params, new JsonHttpResponseHandler("UTF-8") {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    super.onFailure(statusCode, headers, responseString, throwable);
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    throwable.printStackTrace();
                    if (onHttpListner != null) onHttpListner.onHttpListener(falsegetErrorJson(HTTP_ERROR));
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                    super.onSuccess(statusCode, headers, response);
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    if (onHttpListner != null) {
                        if (statusCode == HTTP_OK) {
                            response = (response == null ? new JSONObject() : response);
                            onHttpListner.onHttpListener(true, response);
                        } else onHttpListner.onHttpListener(false, response);
                    }
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    super.onSuccess(statusCode, headers, responseString);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (onHttpListner != null) onHttpListner.onHttpListener(falsegetErrorJson(HTTP_ERROR));
        }
    }
    //**************************************************************************************************************************
    //                                                                                                  其他访问服务器的方法
    //**************************************************************************************************************************
    /**
     * get请求,返回String
     */
    public static void get_AbsoluteUrl_String(final String url, RequestParams params, final OnHttpListener<String> onHttpListner) {
        if (params == null) params = new RequestParams();
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.setTimeout(5000);
        try {
            asyncHttpClient.get(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                    if (onHttpListner != null) onHttpListner.onHttpListener(false, arg2 == null ? "error" : new String(arg2));
                }
                @Override
                public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                    if (arg0 == HTTP_OK) {
                        if (onHttpListner != null) onHttpListner.onHttpListener(true, arg2 == null ? "error" : new String(arg2));
                    } else {
                        if (onHttpListner != null) onHttpListner.onHttpListener(false, arg2 == null ? "error" : new String(arg2));
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (onHttpListner != null) onHttpListner.onHttpListener(false"");
        }
    }
    /**
     * get请求,返回JSONArray
     */
    public static void get_AbsoluteUrl_JSONArray(final String absoulteUrl, RequestParams params, final OnHttpListener<JSONArray> onHttpListner) {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.setTimeout(5000);
        asyncHttpClient.get(absoulteUrl, params, new JsonHttpResponseHandler("UTF-8") {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                if (onHttpListner != null) {
                    if (statusCode == HTTP_OK) {
                        response = (JSONArray) (response == null ? (new JSONObject()) : response);
                        onHttpListner.onHttpListener(true, response);
                    } else onHttpListner.onHttpListener(false, response);
                }
            }
        });
    }
    /**
     * https post请求
     */
    public static void httpsPost(String url, RequestParams params, final OnHttpListener<String> onHttpListener) {
        if (params == null) params = new RequestParams();
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        KeyStore trustStore = null;
        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        } catch (KeyStoreException e1) {
            e1.printStackTrace();
        }
        try {
            trustStore.load(nullnull);
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (CertificateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        MySSLSocketFactory socketFactory = null;
        try {
            socketFactory = new MySSLSocketFactory(trustStore);
        } catch (KeyManagementException e1) {
            e1.printStackTrace();
        } catch (UnrecoverableKeyException e1) {
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (KeyStoreException e1) {
            e1.printStackTrace();
        }
        socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        asyncHttpClient.setSSLSocketFactory(socketFactory);
        asyncHttpClient.setTimeout(5000);
        try {
            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                    if (onHttpListener != null) onHttpListener.onHttpListener(false, arg2 == null ? "error" : new String(arg2));
                }
                @Override
                public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                    if (arg0 == HTTP_OK) {
                        if (onHttpListener != null) onHttpListener.onHttpListener(true, arg2 == null ? "error" : new String(arg2));
                    } else {
                        if (onHttpListener != null) onHttpListener.onHttpListener(false, arg2 == null ? "error" : new String(arg2));
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if (onHttpListener != null) onHttpListener.onHttpListener(false"");
        }
    }
    //**************************************************************************************************************************
    //                                                                                                           其他方法
    //**************************************************************************************************************************
    /**
     * 根据错误信息生成相应的json对象
     */
    public static JSONObject getErrorJson(String error) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("error", error);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }
    /**
     * 添加ky-value到Requestparams
     */
    public static void addRequestParam(RequestParams params, String key, String value) {
        if (params == null) params = new RequestParams();
        params.add(key, value);
    }
    /**
     * 设置持久化保存cookie
     */
    public static void saveCookie(Context context) {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);
        asyncHttpClient.setCookieStore(cookieStore);
    }
    public interface OnHttpListener<T> {
        public void onHttpListener(boolean httpSuccessed, T obj);
    }
}

AsyncHttp再封装
/**AsyncHttp再封装后的简易工具类*/
public class AsyncXiuHttpHelper {
    //    public static final String SERVER_URL = "api.95xiu.com";
    //    public static final String WEB_SERVER_URL = "chat.95xiu.com";
    //    public static final int LIVE_WEB_PORT = 3016;
    public static final String SERVER_URL = "tapi.95xiu.com";
    public static final String WEB_SERVER_URL = "tapi.95xiu.com";
    public static final int LIVE_WEB_PORT = 3014;
    /**
     * get 请求
     * @param relativeUrl  相对地址,如"/user/loginv2.php"
     * @param params   请求参数
     * @param onHttpListner   成功或失败时的监听,在回调方法中获取返回的数据
     */
    public static void get(final String relativeUrl, RequestParams params, final OnHttpListener<JSONObject> onHttpListner) {
        params = FormatRequestParams(params);
        AsyncHttpHelper.get(SERVER_URL, relativeUrl, params, onHttpListner);
    }
    /**
     *  post 请求
     * @param relativeUrl  相对地址,如"/user/loginv2.php"
     * @param params   请求参数
     * @param onHttpListner   成功或失败时的监听,在回调方法中获取返回的数据
     */
    public static void post(final String relativeUrl, RequestParams params, final OnHttpListener<JSONObject> onHttpListner) {
        params = FormatRequestParams(params);
        AsyncHttpHelper.post(SERVER_URL, relativeUrl, params, onHttpListner);
    }
    /**
     * 返回添加了基础信息的RequestParams
     */
    private static RequestParams FormatRequestParams(RequestParams params) {
        if (params == null) params = new RequestParams();
        //params.put("imei", Properties.IMEI);
        //params.put("channel", Properties.CN);
        //params.put("session_id", AppUser.getInstance().getUser().getuSessionId());
        //params.put("version_code", Properties.VERSION_CODE);
        return params;
    }
}

进度条对话框
/**显示、隐藏进度对话框的工具类*/
public class ProgressDialogUtil {
    private static ProgressDialogView progressDialog;
    /**显示自定义的进度对话框,不可取消*/
    public static void showProgressDialog(Context context, String title, String message) {
        dismissProgressDialog();
        progressDialog = new ProgressDialogView(context);
        progressDialog.setTitle(title);
        progressDialog.setMessage(message);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
    /**显示自定义的进度对话框*/
    public static void showProgressDialog(Context context, String title, String message, boolean cancelable, OnCancelListener cancelListener) {
        dismissProgressDialog();
        progressDialog = new ProgressDialogView(context);
        progressDialog.setTitle(title);
        progressDialog.setMessage(message);
        progressDialog.setCancelable(cancelable);
        progressDialog.setOnCancelListener(cancelListener);
        progressDialog.show();
    }
    /** 取消显示带进度条的对话框 */
    public static void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            try {
                progressDialog.dismiss();
            } catch (IllegalArgumentException e) {
            }
        }
        progressDialog = null;
    }
}





AsyncHttpClient httpURLCon httpClient AsyncTask 访问服务器

标签:

原文地址:http://www.cnblogs.com/baiqiantao/p/5559301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!