浅入浅出Android(014):HTTP GET获取文本内容
16lz
2021-01-25
Androidstudio版本:0.8.6;虚拟机版本:4.*。
1、建立android项目MyApplication
2、修改布局文件activity_my.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MyActivity"> <Button android:id="@+id/button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获取网页内容" /> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/button01"> <TextView android:id="@+id/textview01" android:text="" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </ScrollView></RelativeLayout>
3、添加联网权限
在AndroidManifest.xml添加<uses-permission android:name="android.permission.INTERNET" />,文件最终内容是:<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.letian.myapplication" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MyActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
4、修改MyActivity.java
package com.example.letian.myapplication;import android.app.Activity;import android.os.Bundle;import android.os.StrictMode;import android.view.View;import android.widget.Button;import android.widget.TextView;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import java.io.BufferedReader;import java.io.InputStreamReader;public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); final Button btn01 = (Button) this.findViewById(R.id.button01); final TextView tv01 = (TextView) this.findViewById(R.id.textview01); btn01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tv01.setText(getUrlContent("http://www.oschina.net/")); } }); } private String getUrlContent(String url) { HttpGet getRequest = new HttpGet(url); getRequest.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"); try { HttpResponse response = new DefaultHttpClient().execute(getRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; //存储读取的一行内容 String NL = System.getProperty("line.separator"); //换行符 while ((line = in.readLine()) != null) { sb.append(line+NL); } in.close(); return sb.toString(); } else { return "读取失败:\n"+response.getStatusLine().getStatusCode(); } } catch (Exception e) { return "读取失败:\n"+e.toString(); } }}
5、但是运行结果并不令人满意,出现异常
网页请求时一个阻塞的过程,如果时间过长会造成程序假死,所以产生了该异常。这个异常在较新版本的Android中才提出。
6、一个并不推荐的解决办法
该方法可能会造成程序假死,所以最好不要在app中使用该方法。
在onCreate()的适当位置添加如下内容:
if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);}app运行结果如下:
7、使用线程的方法来解决(推荐)
将MyActivity.java修改如下:
package com.example.letian.myapplication;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.TextView;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import java.io.BufferedReader;import java.io.InputStreamReader;public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); final Button btn01 = (Button) this.findViewById(R.id.button01); final TextView tv01 = (TextView) this.findViewById(R.id.textview01); final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); tv01.setText(data.getString("value")); } }; final Runnable runnable = new Runnable(){ @Override public void run() { String result = getUrlContent("http://www.oschina.net/"); Message msg = new Message(); Bundle data = new Bundle(); data.putString("value", result); msg.setData(data); handler.sendMessage(msg); } }; btn01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(runnable).start(); } }); } /** * 获取url对应的网页内容 * @param url * @return */ private String getUrlContent(String url) { HttpGet getRequest = new HttpGet(url); getRequest.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"); try { HttpResponse response = new DefaultHttpClient().execute(getRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; //存储读取的一行内容 String NL = System.getProperty("line.separator"); //换行符 while ((line = in.readLine()) != null) { sb.append(line+NL); } in.close(); return sb.toString(); } else { return "读取失败:\n"+response.getStatusLine().getStatusCode(); } } catch (Exception e) { return "读取失败:\n"+e.toString(); } }}
参考:
http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception
Android编程典型实例与项目开发吴亚峰等编
更多相关文章
- 自定义Android的Dialog
- Android(安卓)so 文件全部报错:Duplicate resources
- android中的hdpi,ldpi,mdpi
- Android之Mina频繁发送心跳包
- Ubuntu下搭建Android开发平台
- Android(安卓)NDK 调试
- android错误信息大整理
- Android(安卓)版本速查表
- [Android][工具类]AppUtils