当前访客身份:游客 [ 登录  | 注册加入尚学堂]
直播
新闻资讯

Android HTTP GET获取文本内容

helloworld 发表于 2年前  | 评论(1 )| 阅读次数(1181 )|   0 人收藏此文章,   我要收藏
Android studio版本: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>



ScrollView用于给Textview添加滚动条。

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、一个并不推荐的解决办法


在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编程典型实例与项目开发 吴亚峰等编


****************************************

原文链接:http://my.oschina.net/letiantian/blog/323156

分享到:0
关注微信,跟着我们扩展技术视野。每天推送IT新技术文章,每周聚焦一门新技术。微信二维码如下:
微信公众账号:尚学堂(微信号:bjsxt-java)
北京总部地址:北京市海淀区西三旗桥东建材城西路85号神州科技园B座三层尚学堂 咨询电话:400-009-1906 010-56233821
Copyright 2007-2015 北京尚学堂科技有限公司 京ICP备13018289号-1 京公网安备11010802015183