14 使用HttpConnection获取网络网页源代码

来源:互联网 发布:java语言的优势 编辑:程序博客网 时间:2024/05/19 00:50

首先我们使用工具类将byte转换为String 与将InputStream转换为byte。

package org.china.java.util;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class HtmlUtil {public static String getHtml(String address)throws Exception{URL url=new URL(address);HttpURLConnection conn=(HttpURLConnection) url.openConnection();conn.setReadTimeout(5000);conn.setRequestMethod("GET");int code=conn.getResponseCode();if(code==200){InputStream is=conn.getInputStream();byte[] result=StreamTool.getBytes(is);return new String(result);}else{throw new IllegalStateException("获取数据错误!");}}}

package org.china.java.util;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.InputStreamReader;public class StreamTool {/** * 把一个input里面的内容转换成一个byte[] */public static byte[] getBytes(InputStream is)throws Exception{ByteArrayOutputStream bos=new ByteArrayOutputStream();byte[] buffer=new byte[1024];int len=0;while((len=is.read(buffer))!=-1){bos.write(buffer, 0, len);}is.close();bos.flush();return bos.toByteArray();}@Deprecatedpublic static byte[] getBytesByte(InputStream is)throws Exception{BufferedReader buf=new BufferedReader(new InputStreamReader(is));return buf.readLine().getBytes();}}

Activity代码

package org.china.java.viewnetcode;import org.china.java.util.HtmlUtil;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {private EditText et_address;private Button btn;private TextView tv_content;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);super.setContentView(R.layout.activity_main);this.et_address=(EditText) super.findViewById(R.id.et_address);this.btn=(Button) super.findViewById(R.id.btn);this.tv_content=(TextView) super.findViewById(R.id.tv_content);this.btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String address=et_address.getText().toString().trim();if("".equals(address) || null==address){Toast.makeText(getApplicationContext(),"地址不能为空",Toast.LENGTH_SHORT).show();return ;}try {String result=HtmlUtil.getHtml(address);tv_content.setText(result);} catch (Exception e) {Toast.makeText(getApplicationContext(),"获取数据失败",Toast.LENGTH_LONG).show();e.printStackTrace();}}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

布局文件和所需要的权限配置文件

<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:orientation="vertical"    tools:context=".MainActivity" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="请输入地址" /><EditText     android:id="@+id/et_address"    android:text="http://www.baidu.com"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    /><Button     android:id="@+id/btn"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="查看"    /><ScrollView     android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <TextView         android:id="@+id/tv_content"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        /></ScrollView>        </LinearLayout>

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="org.china.java.viewnetcode"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <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="org.china.java.viewnetcode.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>


0 0
原创粉丝点击