鱼C论坛

 找回密码
 立即注册
查看: 2024|回复: 0

android学习笔记之访问互联网

[复制链接]
发表于 2014-11-6 21:28:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 青玄 于 2014-11-6 21:29 编辑

访问互联网读取网页代码:
所需要的权限:
  1. <uses-permission android:name="android.permission.INTERNET"/>
复制代码


读取内容的类:
  1. package com.example.loadhtml_test.util;

  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;

  4. public class Utils {

  5.         public static String getInternetData(InputStream is)
  6.         {
  7.                 try
  8.                 {
  9.                         ByteArrayOutputStream baos = new ByteArrayOutputStream();   //字节数据输出流
  10.                         byte[] buffer = new byte[1024];   //字节数组
  11.                         int len = -1;
  12.                         while((len = is.read(buffer)) != -1)   //将输入流里面的内容读到字节数组里面
  13.                         {  
  14.                                 baos.write(buffer, 0, len);  //再将字节数组里面的内容写到字节数组输出流里面
  15.                         }
  16.                         String content = new String(baos.toByteArray(), "GBK");  //将这个内容转化为字符串并设置它的编码
  17.                         if(content.contains("content="text/html;charset=utf-8""))  //如果编码为utf-8的话
  18.                         {
  19.                                 return new String(baos.toByteArray(),"utf-8");   //就设置utf-8编码
  20.                         }
  21.                         return content;
  22.                 }catch(Exception e)
  23.                 {
  24.                         e.printStackTrace();
  25.                         return null;
  26.                 }
  27.         }
  28. }
复制代码



本程序的主类:
  1. package com.example.loadhtml_test;

  2. import java.io.InputStream;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;

  5. import com.example.loadhtml_test.util.Utils;

  6. import android.os.Bundle;
  7. import android.os.Handler;
  8. import android.os.Message;
  9. import android.app.Activity;
  10. import android.text.TextUtils;
  11. import android.view.Menu;
  12. import android.view.View;
  13. import android.widget.EditText;
  14. import android.widget.TextView;
  15. import android.widget.Toast;

  16. public class MainActivity extends Activity {

  17.         private TextView tv;
  18.         private EditText et;
  19.         private Handler handler;
  20.         
  21.         @Override
  22.         protected void onCreate(Bundle savedInstanceState) {
  23.                 super.onCreate(savedInstanceState);
  24.                 setContentView(R.layout.activity_main);
  25.                 this.tv = (TextView) this.findViewById(R.id.ty);
  26.                 this.et = (EditText) this.findViewById(R.id.et);
  27.                 handler = new Handler(){

  28.                         @Override
  29.                         public void handleMessage(Message msg) {   //主线程中接收子线程发来的消息方法
  30.                                 // TODO Auto-generated method stub
  31.                                 if(msg.what == 1)
  32.                                 {
  33.                                         tv.setText((String)msg.obj);
  34.                                 }else if(msg.what == 2)
  35.                                 {
  36.                                         Toast.makeText(MainActivity.this, "网络链接有误", Toast.LENGTH_LONG).show();
  37.                                 }
  38.                         }
  39.                         
  40.                 };
  41.         }
  42.         
  43.         public void showData(View v)   //点击事件的方法
  44.         {
  45.                 final String path = et.getText().toString().trim();  //获取网址路径
  46.                 if(!TextUtils.isEmpty(path))
  47.                 {
  48.                         new Thread()   //开一个子线程
  49.                         {
  50.                                 public void run()
  51.                                 {
  52.                                         try
  53.                                         {
  54.                                                 URL url = new URL(path);   //得到网址路径,并把它装在URL里面
  55.                                                 //通过url获得HttpURLConnection对象
  56.                                                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  57.                                                 conn.setRequestMethod("GET");   //设置请求的方法
  58.                                                 conn.setConnectTimeout(5000);   //设置链接的时长
  59.                                                 conn.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
  60.                                                 conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0)");
  61.                                                 int code = conn.getResponseCode();   //获得服务器发过来的返回码
  62.                                                 
  63.                                                 if(code == 200)   //如果是200的话
  64.                                                 {
  65.                                                         final InputStream is = conn.getInputStream();   //从这个链接对象里面获取输入流
  66.                                                         final String content = Utils.getInternetData(is);  //调用这个方法获取网页的代码
  67.                                                         if(content != null)
  68.                                                         {
  69.                                                                 Message msg = Message.obtain();   //得到消息对象
  70.                                                                 msg.what = 1;   //设置消息
  71.                                                                 msg.obj = content;  //给消息一个对象传过去
  72.                                                                 handler.sendMessage(msg);   //发送消息
  73.                                                         }else
  74.                                                         {
  75.                                                                 Message msg = Message.obtain();
  76.                                                                 msg.what = 2;
  77.                                                                 handler.sendMessage(msg);
  78.                                                         }
  79.                                                 }
  80.                                         }catch(Exception e)
  81.                                         {
  82.                                                 e.printStackTrace();
  83.                                         }
  84.                                 }
  85.                         }.start();
  86.                 }else
  87.                 {
  88.                         Toast.makeText(this, "获取内容失败", Toast.LENGTH_LONG).show();
  89.                 }
  90.         }
  91. }
复制代码
3.xml布局文件:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.            android:orientation="vertical"
  6.     tools:context=".MainActivity" >

  7. <ScrollView
  8.      android:layout_width="match_parent"
  9.      android:layout_height="match_parent"
  10.      android:layout_weight="20"
  11.      >
  12.      <TextView
  13.          android:id="@+id/ty"
  14.          android:layout_width="match_parent"
  15.          android:layout_height="match_parent"
  16.          />
  17. </ScrollView>   
  18. <EditText
  19.      android:id="@+id/et"
  20.      android:layout_width="match_parent"
  21.      android:layout_height="wrap_content"
  22.      />
  23. <Button
  24.      android:layout_width="match_parent"
  25.      android:layout_height="wrap_content"
  26.      android:onClick="showData"
  27.      android:text="获得网页内容"
  28.      />

  29. </LinearLayout>
复制代码

QQ截图20141106212635.png



评分

参与人数 1荣誉 +5 收起 理由
拈花小仙 + 5 感谢楼主无私奉献!

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-28 03:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表