简单封装Http的Get和Post请求

虽然现在有许多成型的Http框架,比如OkHttp、Volley,但是有时候我们仅仅需要一个很简单的功能,比如仅需要一个Get和Post,那么我们用这些库就有种杀机用宰牛刀的感觉。于是就想着自己去封装一个简单的类来实现这部分功能。

以下是我的工具类:
public class HttpUtil {

    private HttpUtil() {
    }

    /**
     * get方法请求数据
     *
     * @param url      请求地址
     * @param params   请求参数
     * @param callBack 回调接口
     */
    public static void get(final String url, final Map params, final HttpResponseCallBack callBack) {
        if (callBack != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //拼装请求参数列表
                        final StringBuilder sb = new StringBuilder(64);
                        if (params != null) {
                            sb.append("?");
                            for (Map.Entry entry : params.entrySet()) {
                                sb.append(entry.getKey());
                                sb.append("=");
                                sb.append(entry.getValue());
                                sb.append("&");
                            }
                            sb.deleteCharAt(sb.length() - 1);
                        }

                        //构建新连接
                        URL httpUrl = new URL(url + sb.toString());
                        LogUtil.i(url + sb.toString());
                        HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                        conn.setConnectTimeout(3000);
                        conn.setReadTimeout(3000);
                        conn.setRequestMethod("GET");
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), "UTF-8"));

                        //接受返回数据
                        sb.setLength(0);
                        String strTemp;
                        while ((strTemp = br.readLine()) != null) {
                            sb.append(strTemp).append('\n');
                        }

                        conn.disconnect();

                        AsyncRun.run(new Runnable() {
                            @Override
                            public void run() {
                                callBack.onSuccess(sb.toString());
                            }
                        });

                    } catch (final IOException e) {
                        AsyncRun.run(new Runnable() {
                            @Override
                            public void run() {
                                callBack.onFailure("失败信息:", e);
                            }
                        });
                    }
                }
            }).start();
        }
    }

    /**
     * post方法请求数据
     *
     * @param url      请求地址
     * @param params   请求参数
     * @param callBack 回调地址
     */
    public static void post(final String url, final Map params, final HttpResponseCallBack callBack) {
        if (callBack != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final StringBuilder sb = new StringBuilder(64);

                        URL httpUrl = new URL(url);
                        HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                        conn.setConnectTimeout(3000);
                        conn.setReadTimeout(3000);
                        conn.setRequestMethod("POST");
                        conn.setDoOutput(true);

                        //拼装请求参数列表
                        if (params != null) {
                            for (Map.Entry entry : params.entrySet()) {
                                sb.append(entry.getKey());
                                sb.append("=");
                                sb.append(entry.getValue());
                                sb.append("&");
                            }
                            sb.deleteCharAt(sb.length() - 1);
                            conn.getOutputStream().write(sb.toString().getBytes());
                        }

                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), "UTF-8"));

                        //接受返回数据
                        sb.setLength(0);
                        String strTemp;
                        while ((strTemp = br.readLine()) != null) {
                            sb.append(strTemp).append('\n');
                        }

                        conn.disconnect();

                        AsyncRun.run(new Runnable() {
                            @Override
                            public void run() {
                                callBack.onSuccess(sb.toString());
                            }
                        });

                    } catch (final IOException e) {
                        AsyncRun.run(new Runnable() {
                            @Override
                            public void run() {
                                callBack.onFailure("失败信息:", e);
                            }
                        });
                    }
                }
            }).start();
        }
    }

    /**
     * 获取回调
     */
    public interface HttpResponseCallBack {
        void onSuccess(String result);

        void onFailure(String result, Exception e);
    }
}

因为我么的网络操作不可以在UI线程中执行,所以我们考虑在新线程中通过调用主线程的Handler把我们需要做的操作post到主线程中就可以了,我们进行一个简单的封装:
public final class AsyncRun {
    public static void run(Runnable runnable){
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(runnable);
    }
}

这个时候我们就可以在业务代码中进行调用(这个例子是百度CSDN这个关键词):

HashMap request = new HashMap<>(2);
                map.put("ie", "UTF-8");
                map.put("wd", "CSDN");
                HttpUtil.post("https://www.baidu.com/s", request, new HttpUtil.HttpResponseCallBack() {
                    @Override
                    public void onSuccess(String result) {
                        Log.i("TAG", result);
                        //这里已经实在主线程中运行了
                        //所以完全可以直接调用TextView之类的控件来显示我们的回调内容
                    }

                    @Override
                    public void onFailure(String result, Exception e) {
                        Log.i("TAG",  result + e.toString());
                    }
                });



为了简单起见,我把参数用一个Map来封装,这样不仅代码看起来更加简介,使用的时候已能够很方便了!





你可能感兴趣的:(android)