Android URL类的使用

//注意:Android 4.0以后的版本默认不允许在主线程中访问网络,因此本例需要在android2.3及其以下版本中使用

URL 类的构造方法(常用)

public URL(String Spec) 例如 URL url=new URL("http://www.baidu.com");


URL类的常用方法

String getProtocol()

String getHost()

String getPort()

public final InuputStream openStream() //用于读取url资源的输入流


以下例子为输入url 在textview中显示网页数据流的demo:

package com.example.urlfoundation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button btn;
	private TextView txtshow;
	private EditText edt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn=(Button)findViewById(R.id.btn);
		txtshow=(TextView)findViewById(R.id.txtshow);
		edt=(EditText)findViewById(R.id.edt);
		btn.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View view) {
				String inputUrl="http://www.baidu.com";
				if(inputUrl.equals(""))
					Toast.makeText(MainActivity.this, "请输入网址!", Toast.LENGTH_SHORT).show();
				else{
					String result="";
					try {
						URL url=new URL(inputUrl);//
						result+="协议名:"+url.getProtocol()+"\n";//URL类的常用方法getProtocol()getHost()getPort()
						result+="主机号:"+url.getHost()+"\n";
						result+="端口号:"+url.getPort()+"\n";
						txtshow.setText(result);
						InputStream in=url.openStream();//url非常重要的方法 openStream()返回输入流 用于读取网页流内容
						BufferedReader br=new BufferedReader(new InputStreamReader(in));
						String line="";
						while((line=br.readLine())!=null)
						{
							result+=line;
						}
						txtshow.setText(result);
						br.close();
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
			}});
		
	}

	@Override
	public 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;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

Android URL类的使用_第1张图片

你可能感兴趣的:(android)