工具类
package cs.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamUtil {
public static byte [] read(InputStream inStream) throws IOException{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte [] buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer))!=-1){
outStream.write(buffer);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
}
业务类
package cs.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import cs.util.StreamUtil;
public class HtmlService {
public static String gethtml(String path) throws IOException{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");
while(conn.getResponseCode() == 200){
InputStream inStrem = conn.getInputStream();
byte [] html = StreamUtil.read(inStrem);
String data = new String (html,"UTF-8");
return data;
}
return null;
}
}
Activity
package com.example.htmlview;
import java.io.IOException;
import cs.service.HtmlService;
import android.app.Activity;
import android.os.Bundle;
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 {
EditText htmlpath;
Button ok;
TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
htmlpath = (EditText) this.findViewById(R.id.htmlpath);
ok = (Button) this.findViewById(R.id.ok);
show = (TextView) this.findViewById(R.id.show);
ok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String path = htmlpath.getText().toString().trim();
try {
String data = HtmlService.gethtml(path);
show.setText(data);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "读取失败", 1).show();
e.printStackTrace();
}
}
});
}
}