1.android的API提供了访问网络的一个类HttpURLConnection

2.通过发送GET请求获取服务器返回的html代码

3.先看看布局文件,如下所示,

<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/activity_main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><EditTextandroid:id="@+id/et"android:layout_width="match_parent"android:layout_height="wrap_content"/><Buttonandroid:onClick="get"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="获取源码"/><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/tv"android:layout_width="match_parent"android:layout_height="match_parent"android:textColor="#00f"android:hint="源码显示"/></ScrollView></LinearLayout>

布局样子:

4.下来是清单文件,记得连接网络要添加权限

5.1再看java代码,MainActivity的

packagecom.market.source;importandroid.app.Activity;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.TextView;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.ProtocolException;importjava.net.URL;importjava.net.URLConnection;importbutterknife.BindView;importbutterknife.ButterKnife;publicclassMainActivityextendsActivity{@BindView(R.id.et)EditTextet;@BindView(R.id.tv)TextViewtv;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ButterKnife.bind(this);}publicvoidget(Viewvew)throwsIOException{finalStringstr=et.getText().toString().trim();newThread(){@Overridepublicvoidrun(){//1.请求地址urlURLurl=null;try{url=newURL(str);//2.获取对这个地址的连接HttpURLConnectioncon=(HttpURLConnection)url.openConnection();//3.设置对这个地址的请求,GET请求con.setRequestMethod("GET");//4.设置请求参数con.setConnectTimeout(5000);//5.获取服务器的响应intcode=con.getResponseCode();//6.根据响应吗,判断请求成功还是失败,200成功if(code==200){//7.成功的话,服务器一流的形式返回数据InputStreaminputStream=con.getInputStream();//8.这个流是字节流,需要我们转换为字符流才可以认识finalStringinfo=StreamTool.StreamtoString(inputStream);Log.e("MainActivity",info);runOnUiThread(newRunnable(){@Overridepublicvoidrun(){tv.setText(info);}});}}catch(MalformedURLExceptione){e.printStackTrace();}catch(ProtocolExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}}.start();}}

5.2工具类,用来将一个流转化为字符串

publicclassStreamTool{publicstaticStringStreamtoString(InputStreaminputStream){intlen=-1;byte[]buffer=newbyte[1024];//内存数组输出流ByteArrayOutputStreambaos=newByteArrayOutputStream();try{while((len=inputStream.read(buffer))!=-1){baos.write(buffer,0,len);}Stringstr=newString(baos.toByteArray());returnstr;}catch(IOExceptione){e.printStackTrace();}finally{try{inputStream.close();}catch(IOExceptione){e.printStackTrace();}}returnnull;}}

6.运行效果查看