访问网络文本

package com.itheima.text;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetService {
	
	public String getText(String path) throws Exception {		// 根据path访问网络, 得到服务器写回的文本
		URL url = new URL(path);								// 把字符串路径封装成URL对象
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();		// 打开一个连接对象
		
		int code = conn.getResponseCode();						// 连接服务器, 得到相应吗
		if (code == 200) {										// 判断请求是否成功
			InputStream in = conn.getInputStream();				// 获取输入流
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[8192];
			int length;
			while((length = in.read(buffer)) != -1) 			// 从网络读取数据
				out.write(buffer, 0, length);					// 把数据写到内存
			in.close();
			out.close();
			
			byte[] data = out.toByteArray();					// 获取内存中的所有数据
			String text = new String(data, "UTF-8");			// 把字节数据解码为字符串
			return text;
		}
		throw new RuntimeException("访问网络出错: " + code);
	}

}

package com.itheima.text;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText pathET;
	private NetService service;
	private TextView textTV;
	private Handler handler = new Handler();	// 处理器, 可以在线程之间通信

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		textTV = (TextView) findViewById(R.id.textTV);
		pathET = (EditText) findViewById(R.id.pathET);
		service = new NetService();
	}
	
	public void go(View v) {
		final ProgressDialog dialog = new ProgressDialog(this);
		dialog.setCancelable(false);	// 设置进度条不能被取消
		dialog.show();					// 显示进度条
		
		new Thread(){
			public void run() {
				try {
					String path = pathET.getText().toString();		// 获取地址
					final String text = service.getText(path);		// 访问网络(4.0以上不能主线程联网), 得到文本
					
					handler.post(new Runnable(){					// 向创建该handler的线程(main)发送一个Runnable, 主线程执行run()
						public void run() {
							dialog.dismiss();						// 取消
							textTV.setText(text);					// 把文本放到TextView中(主线程创建的视图, 只能在主线程修改)
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), "服务器忙!", Toast.LENGTH_SHORT).show();
				}
			}
		}.start();
	}

}

布局--
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/goBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:onClick="go"
        android:text="Go" />

    <EditText
        android:id="@+id/pathET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/goBT"
        android:layout_toLeftOf="@id/goBT"
        android:hint="请输入要访问的地址"
        android:inputType="textUri"
        android:text="http://192.168.1.228:8080/05.Web/text.txt" />

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/pathET" >

        <TextView
            android:id="@+id/textTV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textSize="20sp" />
    </ScrollView>

</RelativeLayout>
 <uses-permission android:name="android.permission.INTERNET"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值