HttpURLConnection读取网页文件

时间:2023-03-10 03:42:17
HttpURLConnection读取网页文件

一.关键代码

public class MainActivity extends Activity {

    TextView content;
private static final int SHOWRESPONSE = ; Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SHOWRESPONSE:
String response = (String)msg.obj;
content.setText(response);
break;
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); content = (TextView)findViewById(R.id.context);
} protected void myClick(View v){
if( v.getId() == R.id.btn ){
sendRequest();
}
} private void sendRequest(){ new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout();
connection.setReadTimeout();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while( (line = reader.readLine()) != null ){
response.append(line);
}
Message msg = handler.obtainMessage();
msg.what = SHOWRESPONSE;
msg.obj = response.toString();
handler.sendMessage(msg); }catch (Exception e){
e.printStackTrace();
}finally {
if(connection != null){
connection.disconnect();
}
}
}
}).start();
}
}

二.布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="com.aotian.guo.httpurlconnectiondemo.MainActivity"> <Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/btn"
android:onClick="myClick"/> <ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"> <TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/context"/>
</ScrollView>
</RelativeLayout>

三.所需权限

<uses-permission android:name="android.permission.INTERNET" />