• 01_网页源码查看器基本实现


     

     

    安卓上面敲127.0.0.1或者是localhost是不行的,安卓上面的localhost/127.0.0.1默认是10.0.2.2.有些第三方的模拟器可能不是这个值。安卓自带的模拟器肯定是没问题的。如果是第三方的模拟器自己练习一下可以搞一个路由器连接一下,让你当前的机器有一个地址。路由还是比较好搞的,把你的手机共享一下wifi。把所有的设备都连接到你的手机上,组成一个局域网,你把流量关了就可以了。

     联网的API叫做HttpURLConnection.

    Firefox脱机工作之后文档的查询会快很多.

    HttpURLConnection代表我当前用的协议是Http协议。

    An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance. 

    这个就是HttpURLConnection.

    按照如下的方式使用HttpURLConnection这个类:

    Uses of this class follow a pattern:
    
        Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
        Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
        Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream().
        Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
        Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused. 

    小例子

    For example, to retrieve the webpage at http://www.android.com/:
    
       URL url = new URL("http://www.android.com/");
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
       try {
         InputStream in = new BufferedInputStream(urlConnection.getInputStream());
         readStream(in);
        finally {
         urlConnection.disconnect();
       }
     }
    [2017-06-20 05:20:54 - Day08_01_网页源码查看器] Android Launch!
    [2017-06-20 05:20:54 - Day08_01_网页源码查看器] adb is running normally.
    [2017-06-20 05:20:54 - Day08_01_网页源码查看器] Performing com.itheima.htmlcodeviewer.MainActivity activity launch
    [2017-06-20 05:20:55 - Day08_01_网页源码查看器] Automatic Target Mode: launching new emulator with compatible AVD '2.3'
    [2017-06-20 05:20:55 - Day08_01_网页源码查看器] Launching a new emulator with Virtual Device '2.3'
    [2017-06-20 05:20:55 - Emulator] emulator: Failed to open the HAX device!
    [2017-06-20 05:20:55 - Emulator] HAX is not working and emulator runs in emulation mode
    [2017-06-20 05:20:55 - Emulator] 
    [2017-06-20 05:20:55 - Emulator] emulator: Open HAX device failed
    [2017-06-20 05:20:55 - Emulator] 
    [2017-06-20 05:20:56 - Emulator] emulator: emulator window was out of view and was recentered
    [2017-06-20 05:20:56 - Emulator] 
    [2017-06-20 05:20:56 - Emulator] bind: Permission denied
    [2017-06-20 05:20:56 - Day08_01_网页源码查看器] New emulator found: emulator-5556
    [2017-06-20 05:20:56 - Day08_01_网页源码查看器] Waiting for HOME ('android.process.acore') to be launched...
    [2017-06-20 05:21:27 - Day08_01_网页源码查看器] HOME is up on device 'emulator-5556'
    [2017-06-20 05:21:27 - Day08_01_网页源码查看器] Uploading Day08_01_网页源码查看器.apk onto device 'emulator-5556'
    [2017-06-20 05:21:27 - Day08_01_网页源码查看器] Installing Day08_01_网页源码查看器.apk...
    [2017-06-20 05:21:38 - Day08_01_网页源码查看器] Success!
    [2017-06-20 05:21:38 - Day08_01_网页源码查看器] Starting activity com.itheima.htmlcodeviewer.MainActivity on device emulator-5556
    [2017-06-20 05:21:39 - Day08_01_网页源码查看器] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.itheima.htmlcodeviewer/.MainActivity }

    联网就涉及到要花钱,花钱的时候就需要权限。


    package com.itheima.htmlcodeviewer;
    
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    
        private EditText et_url;
        private Button btn_show;
        private TextView tv_code;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            et_url = (EditText) findViewById(R.id.et_url);
            btn_show = (Button) findViewById(R.id.btn_show);
            tv_code = (TextView) findViewById(R.id.tv_code);
            btn_show.setOnClickListener(new MyOnClickListenr());
            
        }
    
        private class MyOnClickListenr implements OnClickListener{
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //获取url
                String path = et_url.getText().toString().trim();
                    try {
                        URL url = new URL(path);
                        //URLConnection openConnection = url.openConnection();
                        HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
                    //} catch (MalformedURLException e) {
                        //设置请求的方法  方法要大写   默认采用的是GET方式请求 
                        openConnection.setRequestMethod("GET");
                        //如果联网之后网络信号不是太好,那就涉及到一直在等,一直在等
                        //有的时候可能会等的时间很长,等的时间很长的话那就有问题了,我究竟等到什么时候算是个结束
                        //设置超时的时间,一旦超过这个时间默认就是连接失败,让它停止下来
                        openConnection.setConnectTimeout(10000);//设置一个连接超时的时间
                        //获取响应码
                        int responseCode = openConnection.getResponseCode();
                        if(responseCode==200){
                            InputStream inputStream = openConnection.getInputStream();//InputStream其实放的就是跟咱们HTML代码相关的内容
                            String stringFromStream = Utils.getStringFromStream(inputStream);
                            tv_code.setText(stringFromStream);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
    
                
                //拿着url联网
                //判断响应码  如果是200 
                //联网后获得响应内容  响应是通过流的方式去返回回来的
                //通过textview 展示对应的内容
                
            }
    
    
            
        }
    
    }
    package com.itheima.htmlcodeviewer;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class Utils {
    //从这个流里面把它内容读出来,读出来之后把它转化成一个String类型的数据
        public static String getStringFromStream(InputStream inputStream) {
            // TODO Auto-generated method stub
            //把流转化为字符串
            ByteArrayOutputStream baso = new ByteArrayOutputStream();
            int len = -1;
            byte[] buffer = new byte[1024];
            try {
                while((len=inputStream.read(buffer))!=-1){
                    baso.write(buffer, 0, len);
                }
                inputStream.close();
                byte[] byteArray  =  baso.toByteArray();
                return new String(byteArray);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }
    
    }
    <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" >
    
        <EditText
            android:id="@+id/et_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textUri" 
            android:hint="请输入网址"
    />
    
        <Button
            android:id="@+id/btn_show"
            android:layout_below="@id/et_url"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查看"/>
        <TextView 
            android:id="@+id/tv_code"
            android:layout_below="@id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />        
    </RelativeLayout>
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.itheima.htmlcodeviewer"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />
        <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="com.itheima.htmlcodeviewer.MainActivity"
                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>
  • 相关阅读:
    makefile vpath变量
    博客园 文章和随笔区别
    Linux OpenGL 实践篇-6 光照
    HTC Vive 叠影器无法创建设备
    Mybatis注解
    MyBatis缓存
    MyBatis关联映射
    动态sql
    MyBatis智能标签
    Mybatis模糊查询及自动映射
  • 原文地址:https://www.cnblogs.com/ZHONGZHENHUA/p/7047059.html
Copyright © 2020-2023  润新知