public class service {
//把输入流的内容转化成字符
public static String readInput(InputStream is){
ByteArrayOutputStream by=new ByteArrayOutputStream();
int len=0;
byte[]buffer =new byte[1024];
try {
while ((len=is.read(buffer))!=-1){
by.write(buffer, 0, len);
}
is.close();
by.close();
byte[] re=by.toByteArray();
return new String(re);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
return "参数错误";
}
}
}
public class MainActivity extends Activity {
protected static final int ERROR = 0;
protected static final int SET = 1;
private EditText et;
private TextView tv;
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==ERROR){
Toast.makeText(getApplicationContext(), "读取错误了亲", 0).show();
}else if(msg.what==SET){
String text=(String) msg.obj;
tv.setText(text);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.et);
tv=(TextView)findViewById(R.id.tv);
}
public void play(View view){
final String path =et.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(getApplicationContext(), "请输入地址", 0).show();
}else{
new Thread(){
public void run(){
try {
URL url =new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
int c=conn.getResponseCode();
if(c==200){
InputStream is=conn.getInputStream();
String s=service.readInput(is);
Message msg=new Message();
msg.what=SET;
msg.obj=s;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg =new Message();
msg.what=ERROR;
handler.sendMessage(msg);
}
}
}.start();
}
}