Android复习03(Get请求访问网络[详解]、获取文章列表)
2020年3月26日 第6周 星期四
https://ke.qq.com/webcourse/index.html#cid=989760&term_id=101085595&taid=14724409&lite=1&vid=5285890800493379095?
mode 1:具體代碼,可聯系我。QQ:386335886
mode 2:https://gitee.com/wang_zhiguo/【老師的Gitee】
目? ?錄
Get請求訪問網絡:案例(獲取網頁源碼并顯示到App上)?
添加網絡訪問權限
網絡訪問 不能 在主線程中
獲取網頁源碼,并輸出到控制臺
只有創建視圖的線程,才可以訪問視圖
獲取網頁源碼,并展示到App上
handler的兩種寫法(官方and非官方)
展示and代碼匯總
運行截圖
activity_main.xml
AndroidManifest.xml
MainActivity.java
玩Android:獲取首頁文章列表
新建Activity
設置Activity的啟動順序
設置Activity的啟動順序---展示
約束布局中添加ListView
WanListActivity.java(第一步)
數據獲取測試
activity_wan_list.xml
WanListActivity.java
查看Json文件(火狐瀏覽器)
定義解析類,存儲解析出來的信息(Article.java)
Alt + Insert 快捷鍵(get、set、構造方法)
解析從網站上獲取的數據
輸出Json解析結果
創建顯示文章的布局
引入通用適配器(CommonAdapter.java、ViewHolder.java)
CommonAdapter.java
ViewHolder.java
設置適配器
ListView展示截圖
WanListActivity.java
點擊ListView中的Item,顯示具體內容
Get請求訪問網絡:案例(獲取網頁源碼并顯示到App上)?
菜鳥教程?7.1.3 Android HTTP請求方式:HttpURLConnection
https://www.runoob.com/w3cnote/android-tutorial-httpurlconnection.html?
添加網絡訪問權限
網絡訪問 不能 在主線程中
獲取網頁源碼,并輸出到控制臺
只有創建視圖的線程,才可以訪問視圖
獲取網頁源碼,并展示到App上
handler的兩種寫法(官方and非官方)
展示and代碼匯總
運行截圖
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:id="@+id/tv_html"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="cn.wangzg.course0602"><!--網絡訪問權限--><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>MainActivity.java
package cn.wangzg.course0602;import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.TextView;import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL;public class MainActivity extends AppCompatActivity {private TextView tv_html;// private Handler handler=new Handler(){ //內存泄露,非建議寫法 // @Override // public void handleMessage(@NonNull Message msg) { // String str= (String) msg.obj; // 接收消息 強轉(String) // tv_html.setText(str); // } // };//官方建議寫法static class MyHandler extends Handler {// WeakReference to the outer class's instance.private WeakReference<MainActivity> mOuter; //WeakReference弱引用public MyHandler(MainActivity activity) {mOuter = new WeakReference<MainActivity>(activity);}@Overridepublic void handleMessage(Message msg) {MainActivity outer = mOuter.get();if (outer != null) {// Do something with outer as your wish.if (msg.what == 1) {String str = (String) msg.obj;outer.tv_html.setText(str);}}}}private MyHandler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);handler = new MyHandler(this); // //main thread // //局部轉全局 Ctrl+alt+F fulltv_html = findViewById(R.id.tv_html);new Thread() {//new thread 新建線程并啟動start()@Overridepublic void run() {String strUrl = "https://www.runoob.com/w3cnote/android-tutorial-httpurlconnection.html";String s = doGet(strUrl);//System.out.println(s); //網絡訪問在主線程中,會報異常。-->耗時操作(文件訪問、網絡訪問)-->子線程//tv_html.setText(s);Message msg = new Message();msg.what = 1;//區分不同的返回值 區分不同的線程 可能有多個線程【了解】msg.obj = s; // 把參數傳遞過去handler.sendMessage(msg);//通過sendMessage發送消息,handler處理消息 與主線程進行通信,需要使用handler}}.start();// tv_html.setText(s); // s設置為全局變量,也會報錯,app直接崩潰}/** 發送Get請求* @param strUrl 請求地址* @return 返回String */private String doGet(String strUrl) {String ret = null;try {URL url = new URL(strUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//conn.setRequestMethod("GET");//默認Get請求,可以省略conn.setConnectTimeout(5000);InputStream is = conn.getInputStream();ret = is2String(is);conn.disconnect();} catch (IOException e) {e.printStackTrace();}return ret;}/** 將流轉為字符串* @param inStream 輸入流* @return 返回字符串* @throws IOException */private String is2String(InputStream inStream) throws IOException {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return new String(outStream.toByteArray(), "UTF-8");}}玩Android:獲取首頁文章列表
新建Activity
設置Activity的啟動順序
設置Activity的啟動順序---展示
約束布局中添加ListView
WanListActivity.java(第一步)
數據獲取測試
activity_wan_list.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".WanListActivity"><ListViewandroid:id="@+id/listArticle"android:layout_width="0dp"android:layout_height="0dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>WanListActivity.java
package cn.wangzg.course0602;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ListView;import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL;public class WanListActivity extends AppCompatActivity {private ListView listArticle;//官方建議寫法static class MyHandler extends Handler {// WeakReference to the outer class's instance.private WeakReference<WanListActivity> mOuter; //WeakReference弱引用public MyHandler(WanListActivity activity) {mOuter = new WeakReference<WanListActivity>(activity);}@Overridepublic void handleMessage(Message msg) {WanListActivity outer = mOuter.get();if (outer != null) {// Do something with outer as your wish.if (msg.what == 1) {String str = (String) msg.obj;//outer.tv_html.setText(str);}}}}private MyHandler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_wan_list);initView();getData();}private void getData() {new Thread() {//new thread 新建線程并啟動start()@Overridepublic void run() {String strUrl = "https://wanandroid.com/article/list/0/json";String s = doGet(strUrl);System.out.println(s); // 網絡訪問在主線程中,會報異常。--》耗時操作(文件訪問、網絡訪問)-->子線程//tv_html.setText(s);// Message msg = new Message(); // msg.what = 1;//區分不同的返回值 區分不同的線程 可能有多個線程【了解】 // msg.obj = s; // 把參數傳遞過去 // handler.sendMessage(msg); // 通過sendMessage發送消息,handler處理消息 與主線程進行通信,需要使用handler}}.start();}private void initView() {handler = new MyHandler(this);listArticle = findViewById(R.id.listArticle);}/** 發送Get請求* @param strUrl 請求地址* @return 返回String */private String doGet(String strUrl) {String ret = null;try {URL url = new URL(strUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//conn.setRequestMethod("GET");//默認Get請求,可以省略conn.setConnectTimeout(5000);InputStream is = conn.getInputStream();ret = is2String(is);conn.disconnect();} catch (IOException e) {e.printStackTrace();}return ret;}/** 將流轉為字符串* @param inStream 輸入流* @return 返回字符串* @throws IOException */private String is2String(InputStream inStream) throws IOException {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return new String(outStream.toByteArray(), "UTF-8");} }查看Json文件(火狐瀏覽器)
https://wanandroid.com/article/list/0/json
定義解析類,存儲解析出來的信息(Article.java)
Alt + Insert 快捷鍵(get、set、構造方法)
package cn.wangzg.course0602;public class Article {private String title;private String shareUser;//分享人private String superChapterName; // 分類名private String chapterName;private String niceDate;private String link;// alt + insert 快捷鍵(get、set、構造方法)@Overridepublic String toString() {return "Article{" +"title='" + title + '\'' +", shareUser='" + shareUser + '\'' +", superChapterName='" + superChapterName + '\'' +", chapterName='" + chapterName + '\'' +", niceDate='" + niceDate + '\'' +", link='" + link + '\'' +'}';}public void setTitle(String title) {this.title = title;}public void setShareUser(String shareUser) {this.shareUser = shareUser;}public void setSuperChapterName(String superChapterName) {this.superChapterName = superChapterName;}public void setChapterName(String chapterName) {this.chapterName = chapterName;}public void setNiceDate(String niceDate) {this.niceDate = niceDate;}public void setLink(String link) {this.link = link;}public String getTitle() {return title;}public String getShareUser() {return shareUser;}public String getSuperChapterName() {return superChapterName;}public String getChapterName() {return chapterName;}public String getNiceDate() {return niceDate;}public String getLink() {return link;} }解析從網站上獲取的數據
輸出Json解析結果
package cn.wangzg.course0602;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ListView;import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList;public class WanListActivity extends AppCompatActivity {private ListView listArticle;private ArrayList<Article> articles;//官方建議寫法static class MyHandler extends Handler {// WeakReference to the outer class's instance.private WeakReference<WanListActivity> mOuter; //WeakReference弱引用public MyHandler(WanListActivity activity) {mOuter = new WeakReference<WanListActivity>(activity);}@Overridepublic void handleMessage(Message msg) {WanListActivity outer = mOuter.get();if (outer != null) {// Do something with outer as your wish.if (msg.what == 1) {String str = (String) msg.obj;//outer.tv_html.setText(str);}}}}private MyHandler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_wan_list);initView();getData();}private void getData() {new Thread() {//new thread 新建線程并啟動start()@Overridepublic void run() {String strUrl = "https://wanandroid.com/article/list/0/json";String s = doGet(strUrl);//System.out.println(s); // 網絡訪問在主線程中,會報異常。--》耗時操作(文件訪問、網絡訪問)-->子線程// 對s中的json數據進行解析。定義list集合 存儲 解析出來的文章的數據articles = parseArticle(s);for (Article a : articles) {System.out.println(a.toString());}//tv_html.setText(s);// Message msg = new Message(); // msg.what = 1;//區分不同的返回值 區分不同的線程 可能有多個線程【了解】 // msg.obj = s; // 把參數傳遞過去 // handler.sendMessage(msg); // 通過sendMessage發送消息,handler處理消息 與主線程進行通信,需要使用handler}}.start();}private ArrayList<Article> parseArticle(String s) {ArrayList<Article> list = new ArrayList<>();Article article;try {JSONObject object = new JSONObject(s);int errCode = object.optInt("errorCode");if (errCode == 0) {JSONArray array = object.optJSONObject("data").optJSONArray("datas");for (int i = 0; i < array.length(); i++) {article = new Article();JSONObject obj = array.optJSONObject(i);article.setTitle(obj.optString("title"));article.setShareUser(obj.optString("shareUser"));article.setSuperChapterName(obj.optString("superChapterName"));article.setChapterName(obj.optString("chapterName"));article.setNiceDate(obj.optString("niceDate"));article.setLink(obj.optString("link"));list.add(article);}} else {return null;}} catch (JSONException e) {e.printStackTrace();}return list;}private void initView() {handler = new MyHandler(this);listArticle = findViewById(R.id.listArticle);}/*** 發送Get請求** @param strUrl 請求地址* @return 返回String*/private String doGet(String strUrl) {String ret = null;try {URL url = new URL(strUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//conn.setRequestMethod("GET");//默認Get請求,可以省略conn.setConnectTimeout(5000);InputStream is = conn.getInputStream();ret = is2String(is);conn.disconnect();} catch (IOException e) {e.printStackTrace();}return ret;}/*** 將流轉為字符串** @param inStream 輸入流* @return 返回字符串* @throws IOException*/private String is2String(InputStream inStream) throws IOException {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return new String(outStream.toByteArray(), "UTF-8");} }創建顯示文章的布局
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/textView"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginStart="16dp"android:layout_marginTop="8dp"android:layout_marginEnd="16dp"android:text="TextView"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="16dp"android:text="分享人:"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView" /><TextViewandroid:id="@+id/textView3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="16dp"android:text="TextView"app:layout_constraintBaseline_toBaselineOf="@+id/textView2"app:layout_constraintStart_toEndOf="@+id/textView2" /><TextViewandroid:id="@+id/textView4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="16dp"android:text="分類:"app:layout_constraintBaseline_toBaselineOf="@+id/textView3"app:layout_constraintStart_toEndOf="@+id/textView3" /><TextViewandroid:id="@+id/textView5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="16dp"android:text="TextView"app:layout_constraintBaseline_toBaselineOf="@+id/textView4"app:layout_constraintStart_toEndOf="@+id/textView4" /> </androidx.constraintlayout.widget.ConstraintLayout>引入通用適配器(CommonAdapter.java、ViewHolder.java)
CommonAdapter.java
package cn.wangzg.course0602;import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter;import java.util.ArrayList;/*** Time: 2019/2/1* Author: wangzhiguo* Description: 功能描述*/ public abstract class CommonAdapter<T> extends BaseAdapter {protected LayoutInflater mInflater;protected Context mContext;protected ArrayList<T> mDatas;protected final int mItemLayoutId;public CommonAdapter(Context context, ArrayList<T> mDatas, int itemLayoutId){mInflater = LayoutInflater.from(context);this.mContext = context;this.mDatas = mDatas;mItemLayoutId = itemLayoutId;}@Overridepublic int getCount() {return mDatas==null?0:mDatas.size();}@Overridepublic T getItem(int position) {return mDatas.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {final ViewHolder viewHolder = getViewHolder(position, convertView,parent);convert(viewHolder, getItem(position));return viewHolder.getConvertView();}public abstract void convert(ViewHolder helper, T item);private ViewHolder getViewHolder(int position, View convertView,ViewGroup parent){return ViewHolder.get(mContext, convertView, parent, mItemLayoutId,position);}public ArrayList<T> getmDatas() {return mDatas;}public void setmDatas(ArrayList<T> mDatas) {this.mDatas = mDatas;notifyDataSetChanged();}public void addmDatas(ArrayList<T> mDatas) {if(this.mDatas==null) {this.mDatas = mDatas;}else {this.mDatas.addAll(mDatas);}notifyDataSetChanged();} }ViewHolder.java
package cn.wangzg.course0602;import android.content.Context; import android.graphics.Bitmap; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView;//import com.bumptech.glide.Glide;/*** Time: 2019/2/1* Author: wangzhiguo* Description: 功能描述*/ public class ViewHolder {private final SparseArray<View> mViews;private View mConvertView;private Context context;private ViewHolder(Context context, ViewGroup parent, int layoutId,int position){this.mViews = new SparseArray<View>();mConvertView = LayoutInflater.from(context).inflate(layoutId, parent,false);//setTagmConvertView.setTag(this);this.context = context;}/*** 拿到一個ViewHolder對象* @param context* @param convertView* @param parent* @param layoutId* @param position* @return*/public static ViewHolder get(Context context, View convertView,ViewGroup parent, int layoutId, int position){if (convertView == null){return new ViewHolder(context, parent, layoutId, position);}return (ViewHolder) convertView.getTag();}/*** 通過控件的Id獲取對于的控件,如果沒有則加入views* @param viewId* @return*/public <T extends View> T getView(int viewId){View view = mViews.get(viewId);if (view == null){view = mConvertView.findViewById(viewId);mViews.put(viewId, view);}return (T) view;}public View getConvertView(){return mConvertView;}/*** 為TextView設置字符串** @param viewId* @param text* @return*/public ViewHolder setText(int viewId, String text){TextView view = getView(viewId);view.setText(text);return this;}/*** 為ImageView設置圖片** @param viewId* @param drawableId* @return*/public ViewHolder setImageResource(int viewId, int drawableId){ImageView view = getView(viewId);view.setImageResource(drawableId);return this;}/*** 為ImageView設置圖片** @param viewId* @param bm* @return*/public ViewHolder setImageBitmap(int viewId, Bitmap bm){ImageView view = getView(viewId);view.setImageBitmap(bm);return this;}/*** 為ImageView設置圖片** @param viewId* @param url* @return*/public ViewHolder setImageByUrl(int viewId, String url){ // Glide.with(context) // .load(url) // .into((ImageView) getView(viewId));return this;} }設置適配器
ListView展示截圖
WanListActivity.java
package cn.wangzg.course0602;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ListView;import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList;public class WanListActivity extends AppCompatActivity {private ListView listArticle;private ArrayList<Article> articles;private CommonAdapter<Article> adapter;//官方建議寫法static class MyHandler extends Handler {// WeakReference to the outer class's instance.private WeakReference<WanListActivity> mOuter;public MyHandler(WanListActivity activity) {mOuter = new WeakReference<WanListActivity>(activity);}@Overridepublic void handleMessage(Message msg) {WanListActivity outer = mOuter.get();if (outer != null) {if (msg.what == 1) {String str = (String) msg.obj;//outer.tv_html.setText(str);outer.adapter.setmDatas(outer.articles);}}}}private MyHandler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_wan_list);initView();getData();}private void getData() {new Thread() {//new thread@Overridepublic void run() {String strUrl = "https://www.wanandroid.com/article/list/0/json";String s = doGet(strUrl);articles = parseArticle(s);for (Article a : articles) {System.out.println(a.toString());}//tv_html.setText(s);// Message msg=new Message(); // msg.what=1;//區分不同的返回值 // //msg.obj=s; // handler.sendMessage(msg);// 對上述4行代碼進行簡化,只能在Activity中進行runOnUiThread(new Runnable() { // 回到主線程執行內容:官方建議寫法+private MyHandler handler; 這些內容,可以不要。@Overridepublic void run() {adapter.setmDatas(articles);}});}}.start();}private ArrayList<Article> parseArticle(String s) {ArrayList<Article> list = new ArrayList<>();Article article;try {JSONObject object = new JSONObject(s);int errCode = object.optInt("errorCode");if (errCode == 0) {JSONArray array = object.optJSONObject("data").optJSONArray("datas");for (int i = 0; i < array.length(); i++) {article = new Article();JSONObject obj = array.optJSONObject(i);article.setTitle(obj.optString("title"));article.setShareUser(obj.optString("shareUser"));article.setSuperChapterName(obj.optString("superChapterName"));article.setChapterName(obj.optString("chapterName"));article.setNiceDate(obj.optString("niceDate"));article.setLink(obj.optString("link"));list.add(article);}} else {return null;}} catch (JSONException e) {e.printStackTrace();}return list;}private void initView() {//handler = new MyHandler(this);listArticle = findViewById(R.id.listArticle);adapter = new CommonAdapter<Article>(this, null, R.layout.item_article) {@Overridepublic void convert(ViewHolder helper, Article item) {helper.setText(R.id.textView, item.getTitle());helper.setText(R.id.textView3, item.getShareUser());helper.setText(R.id.textView5, item.getSuperChapterName() + "/" + item.getChapterName());}};listArticle.setAdapter(adapter); // 設置適配器}/*** 發送Get請求** @param strUrl 請求地址* @return 返回String*/private String doGet(String strUrl) {String ret = null;try {URL url = new URL(strUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//conn.setRequestMethod("GET");//默認,可以省略conn.setConnectTimeout(5000);InputStream is = conn.getInputStream();ret = is2String(is);conn.disconnect();} catch (IOException e) {e.printStackTrace();}return ret;}/*** 將流轉為字符串** @param inStream 輸入流* @return 返回字符串* @throws IOException*/private String is2String(InputStream inStream) throws IOException {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return new String(outStream.toByteArray(), "UTF-8");} }點擊ListView中的Item,顯示具體內容
菜鳥教程 7.5.1 WebView(網頁視圖)基本用法
https://www.runoob.com/w3cnote/android-tutorial-webview.html
?
新建Activity,在其中放置WebView組件,通過WebView打開文章,進行閱讀。
總結
以上是生活随笔為你收集整理的Android复习03(Get请求访问网络[详解]、获取文章列表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android复习02(ListView
- 下一篇: Android复习01(内部存储、外部存