网络请求工具
最近在對以前寫的代碼進行總結,為了方便以后的使用和查看,所以對自己負責模塊的通用代碼進行總結。
在我負責的應用管控中,網絡請求用的是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) {// 因為網絡請求是耗時操作,所以需要另外開啟一個線程來執(zhí)行該任務。new Thread(new Runnable() {@Overridepublic void run() {HttpURLConnection httpURLConnection = null;BufferedReader reader = null;try {// 根據URL地址創(chuàng)建URL對象URL url = new URL(urlString);// 獲取HttpURLConnection對象httpURLConnection = (HttpURLConnection) url.openConnection();// 設置請求方式,默認為GEThttpURLConnection.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) {// 因為網絡請求是耗時操作,所以需要另外開啟一個線程來執(zhí)行該任務。new Thread(new Runnable() {@Overridepublic 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());//發(fā)送請求參數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() {@Overridepublic void onFinish(String response) {LogUtil.d(TAG, "request control list json = " + response);//開始解析網絡請求返回的數據parseJsonData(response);}@Overridepublic void onError(Exception e) {LogUtil.d(TAG, "network request control list failed !!!");} });非常感謝您的耐心閱讀,希望我的文章對您有幫助。歡迎點評、轉發(fā)或分享給您的朋友或技術群。
總結
- 上一篇: 第一行代码学习笔记第三章——UI开发的点
- 下一篇: 第一行代码学习笔记第四章——探究碎片