HttpRequest Get方式請求,創建子線程,並創建HttpCallbackListener接口來實現HttpRequest的返回監聽
1.HttpUtil類
public static void sendHttpRequest(final String address, final HttpCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(address); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); //超時鏈接時間設置為8秒 connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); BufferedReader 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()); } } catch (Exception e) { if (listener != null) { // 回調onError()方法 listener.onError(e); } } finally { if (connection != null) { connection.disconnect(); } } } }).start();
2.HttpCallbackListener接口
public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }