Effect:
layout:
<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" > <EditText android:id="@+id/et_path" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入网址" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="查看" /> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/tv_result" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>
Code:
package org.dreamtech.look; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private EditText et_path; private TextView tv_result; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate (savedInstanceState); setContentView(R.layout.activity_main); et_path = (EditText) findViewById(R.id.et_path); tv_result = (TextView) findViewById(R.id.tv_result); } public void click(View v) { String path = et_path.getText().toString().trim(); if ("".equals(path)) { Toast.makeText(getApplicationContext(), "URL cannot be empty" , Toast.LENGTH_LONG) .show(); } else { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); if (code == 200) { InputStream in = conn.getInputStream(); String content = StreamTools.readStream(in); tv_result.setText(content); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Please check the network connection or the input URL is wrong" , Toast.LENGTH_LONG).show(); } } } }
Read stream tool:
package org.dreamtech.look; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTools { public static String readStream(InputStream in) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = -1; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) != -1) { baos.write(buffer, 0, len); } in.close(); String content = new String(baos.toByteArray()); return content; } }