雖然github上有很多開源的,方便的jar報,用起來也很方便,但我們也需要了解其中的原理,如何自己不用第三方jar包來獲取網絡資源
主要代碼如下: 因為聯網是耗時的操作,所以需要另開一個線程來執行
1 new Thread(){ 2 public void run() { 3 try { 4 5 //首先聲明url連接對象 6 URL url=new URL(path); 7 //獲取HttpURLConnection對象 8 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 9 // connection.setReadTimeout(5000); 10 //設置連接超時時間,毫秒為單位 11 connection.setConnectTimeout(5000); 12 13 //http方式 14 connection.setRequestMethod("GET"); 15 16 //設置http頭屬性 17 connection.setRequestProperty("apikey", "0a37fe84ecb7c6fe98ca3e8ba48b5f24"); 18 //獲取返回碼//200為正常 404 找不到資源 19 int code = connection.getResponseCode(); 20 if(code==200){ 21 22 //獲取字節流 23 InputStream inputStream = connection.getInputStream(); 24 //解析字節流 25 BufferedReader bf=new BufferedReader(new InputStreamReader(inputStream, "utf-8")); 26 StringBuilder sb=new StringBuilder(); 27 String s=null; 28 while ((s=bf.readLine())!=null) { 29 sb.append(s+"\r\n"); 30 } 31 32 //解析json對象 33 JSONObject jsonObject = new JSONObject(sb.toString()); 34 JSONArray jsonArray = jsonObject.getJSONArray("newslist"); 35 for (int i = 0; i < jsonArray.length(); i++) { 36 news n= new news(); 37 JSONObject jsonObject2 = jsonArray.getJSONObject(i); 38 n.setTime(jsonObject2.getString("ctime")); 39 n.setTitle(jsonObject2.getString("title")); 40 n.setDescription(jsonObject2.getString("description")); 41 n.setPicUrl(jsonObject2.getString("picUrl")); 42 n.setUrl(jsonObject2.getString("url")); 43 list.add(n); 44 } 45 46 } 47 } catch (Exception e) { 48 e.printStackTrace(); 49 } 50 }; 51 52 }.start();