网络请求工具

最近在对以前写的代码进行总结,为了方便以后的使用和查看,所以对自己负责模块的通用代码进行总结。

在我负责的应用管控中,网络请求用的是HttpURLConnection,并没有用OkHttp。

网络请求一般就Get和Post请求。

1. 工具类定义
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by salmonzhang on 2018/12/27.
 * HttpURLConnection网络请求工具类
 */

public class HttpUtil {
    private static final String TAG = "HttpUtil";
    public interface HttpCallbackListener {
        //网络请求成功
        void onFinish(String response);

        //网络请求失败
        void onError(Exception e);
    }

    /**
     * Get请求
     */
    public static void sendGetRequest(
            final String urlString, final HttpCallbackListener listener) {
        // 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                BufferedReader reader = null;
                try {
                    // 根据URL地址创建URL对象
                    URL url = new URL(urlString);
                    // 获取HttpURLConnection对象
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    // 设置请求方式,默认为GET
                    httpURLConnection.setRequestMethod("GET");
                    // 设置连接超时
                    httpURLConnection.setConnectTimeout(8000);
                    // 设置读取超时
                    httpURLConnection.setReadTimeout(8000);

                    // 响应码为200表示成功,否则失败。
                    if (httpURLConnection.getResponseCode() == 200) {
                        // 获取网络的输入流
                        InputStream in = httpURLConnection.getInputStream();
                        // 读取输入流中的数据
                        reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        //响应数据
                        if (listener != null) {
                            // 回调onFinish()方法
                            listener.onFinish(response.toString());
                        }
                    } else {
                        LogUtil.i(TAG, "run: 请求失败");
                    }
                }  catch (IOException e) {
                    // 回调onError()方法
                    if (listener != null) {
                        // 回调onError()方法
                        listener.onError(e);
                    }
                    e.printStackTrace();
                } finally {
                    //关流
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (httpURLConnection != null) {
                        // 释放资源
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * Post请求
     */
    public static void sendPostRequest(
            final String urlString,final String data, final HttpCallbackListener listener) {

        // 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url;
                HttpURLConnection httpURLConnection = null;
                BufferedReader reader = null;
                try {
                    url = new URL(urlString);
                    httpURLConnection = (HttpURLConnection) url.openConnection();

                    httpURLConnection.setRequestMethod("POST");

                    httpURLConnection.setConnectTimeout(8000);
                    httpURLConnection.setReadTimeout(8000);

                    // 设置运行输入
                    httpURLConnection.setDoInput(true);
                    // 设置运行输出
                    httpURLConnection.setDoOutput(true);

                    //获取URLConnection对象对应的输出流
                    PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
                    //发送请求参数
                    printWriter.write(data);//data的参数格式xx=xx&yy=yy
                    //flush输出流的缓冲
                    printWriter.flush();
                    printWriter.close();

                    //开始获取数据
                    if (httpURLConnection.getResponseCode() == 200) {
                        InputStream in = httpURLConnection.getInputStream();
                        // 读取输入流中的数据
                        reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        //响应数据
                        if (listener != null) {
                            // 回调onFinish()方法
                            listener.onFinish(response.toString());
                        }
                    } else {
                        LogUtil.i(TAG, "请求失败 ");
                    }
                } catch (IOException e) {
                    if (listener != null) {
                        // 回调onError()方法
                        listener.onError(e);
                    }
                    e.printStackTrace();
                } finally {
                    //关流
                    if (reader != null) {
                        IoCloseUtil.closeAll(reader);
                    }
                    if (httpURLConnection != null) {
                        // 最后记得关闭连接
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }
}
2. 工具类使用
HttpUtil.sendGetRequest(url, new HttpUtil.HttpCallbackListener() {
    @Override
    public void onFinish(String response) {
        LogUtil.d(TAG, "request control list json = " + response);
		//开始解析网络请求返回的数据
        parseJsonData(response);
    }

    @Override
    public void onError(Exception e) {
        LogUtil.d(TAG, "network request control list failed !!!");
    }
});
非常感谢您的耐心阅读,希望我的文章对您有帮助。欢迎点评、转发或分享给您的朋友或技术群。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值