這個框架是自己閑來無事封裝的,主要用于請求json
1請求數據
public class HttpUtil { /** * 下載資源 * @return */ public static byte[] requestURL(String urlStr){ InputStream in = null; ByteArrayOutputStream out = null; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(3000); conn.connect(); if(conn.getResponseCode() == 200){ in = conn.getInputStream(); out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int len; while((len = in.read(buffer)) != -1){ out.write(buffer, 0, len); } //得到下載好的json字符串 return out.toByteArray(); } } catch (Exception e) { e.PRintStackTrace(); } finally { try { if(in != null){ in.close(); } if(out != null){ out.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; }}2基于剛才的類加上接口回調public class DownUtil { /* 創建一個擁有5個線程的線程池 */ private static ExecutorService executor = Executors.newFixedThreadPool(5); private OnDownListener onDownListener; private Handler handler = new Handler(); //設置解析JSON的接口回調 public DownUtil setOnDownListener(OnDownListener onDownListener) { this.onDownListener = onDownListener; return this; } /** * 下載JSON數據 */ public void downJSON(final String url){ executor.submit(new Runnable() { @Override public void run() { //在子線程中執行 byte[] bytes = HttpUtil.requestURL(url); if(bytes != null){ String json = new String(bytes); //解析JSON if(onDownListener != null){ final Object object = onDownListener.paresJson(json); //將解析的結果回傳給主線程 handler.post(new Runnable() { @Override public void run() { //在主線程中執行 onDownListener.downSucc(object); } }); } } } }); } /** * 接口回調 */ public interface OnDownListener{ //解析JSON時回調 Object paresJson(String json); //解析完成后回調 void downSucc(Object object); }}3用法new DownUtil().setOnDownListener(上下文).downJSON(請求的url);重寫以下兩個方法@Override public Object paresJson(String json) {// 這里便是得到的json,你需要對其判斷或者解析 Log.d("print", "onSuccess: -->" + json); return null; } @Override public void downSucc(Object object) {//回到主線程 }
新聞熱點
疑難解答