其实这个工具很多年前都做过了,当时也是因为个人需要,所以开发了这个工具。
现在重新把代码理出来,希望对大家有帮助。后面会把源码分享出来,希望对正在学习android的朋友有所帮助。
用的开发工具android studio3.5.3
使用as创建项目就略过了,太简单。创建一个Empty Activity,会自动生成项目的基础文件。
1,因为这个项目需要联网,所以一定要记得在清单文件里面配置上联网权限。
<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="cn.jianhaozhan.axx">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2,然后把界面写好,需要一个网址输入框,一个点击按钮,一个显示获取代码的文本域。
界面的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<EditText
android:id="@+id/urledit"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:onClick="getsource"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取源码"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/showsource"
android:text="点击按钮后,请稍微等待一会源码就出来了哦!"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
3,然后主要利用httpURLConnection来获取网页数据,代码里有注释了。
package cn.jianhaozhan.axx;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
final private int SUCCESS=0;
final private int FAILED=1;
final private int EXCEPTION=2;
private EditText url_edit;
private TextView getsource;
private Handler handler=new Handler(){
/**
* Subclasses must implement this to receive messages.
*
* @param msg
*/
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SUCCESS:
String content=(String)msg.obj;
getsource.setText(content);
break;
case FAILED:
Toast.makeText(MainActivity.this,"该网址连接不上",Toast.LENGTH_LONG).show();
break;
case EXCEPTION:
Toast.makeText(MainActivity.this,"服务器忙",Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url_edit=(EditText)findViewById(R.id.urledit);
getsource=(TextView)findViewById(R.id.showsource);
}
public void getsource(View view){
new Thread(){
public void run(){
try {
//获取源码路径
String path = url_edit.getText().toString().trim();
//创建Url,用来创建HTTPUrlConnection对象
URL url = new URL(path);
//创建urlconnection对象用来发送或接收
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
//使用GET请求,GET必须大写默认GET
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
httpURLConnection.setRequestProperty("Connection","keep-alive");
httpURLConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
//请求超时时间
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
//获取服务器返回码,200表示成功
int responseCode = httpURLConnection.getResponseCode();
System.out.println(responseCode);
if(responseCode==200){
//服务器数据是以流形式返回,创建个工具类将就转换成字符串
InputStream inputStream=httpURLConnection.getInputStream();
//使用创建的工具类转流为字符串
String content=StreamTools.getString(inputStream);
Message msg=new Message();
msg.what=0;
msg.obj=content;
handler.sendMessage(msg);
}else {
Message msg=new Message();
msg.what=1;
handler.sendMessage(msg);
}
}catch (Exception e){
e.printStackTrace();
Message msg=new Message();
msg.what=2;
handler.sendMessage(msg);
}
}
}.start();
}
}
其中用到了一个工具类将流文件转化成字符串
package cn.jianhaozhan.axx;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTools {
public static String getString(InputStream inputStream) throws Exception {
//字节数组输出流,相当于缓存到内存
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
//创建len记录当前字节内容长度
int len=-1;
//创建字节数组存放字节
byte[] buffer=new byte[1024];
while ((len=inputStream.read(buffer))!=-1){
//用byteArrayOutputStream包装源流写出,然后这个包装的对象就有数据了
byteArrayOutputStream.write(buffer,0,len);
}
inputStream.close();
String content= new String(byteArrayOutputStream.toByteArray());
return content;
}
}
好,一个安卓端获取网页源码的工具就做好了,是不是很简单。
这里只做了最基本的功能,可以做些更人性化的功能,比如等待的圆圈,输入网址自动加上斜杠,就像浏览器那样。
链接:https://pan.baidu.com/s/1aIUUoT1VtLZnWY_c5FE8jg
提取码:87r9
我的v:lb87626