URLConnection

来源:互联网 发布:python哪些教程比较好 编辑:程序博客网 时间:2024/05/21 22:58

URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和URL之间的连接;
程序可以通过该URLConnection实例
【1】向URL发送请求
【2】读取URL引用的资源
步骤如下
【1】调用URL对象openConnection()得到URLConnection对象
【2】设置URLConnection的参数和请求属性
【3】如果只是发送GET请求,建立连接即可;POST方式请求,需要获取URLConnection实例对应的输出流来发送参数
【4】远程资源变为可用,程序可以访问远程资源的头字段,或通过输入流获取资源;

举例获取输入流对象,读取网络;

public class MainActivity extends Activity implements View.OnClickListener {    private static final int URL_CONNECT=0x2154;    private TextView textView;    private Button button_connection;    private Handler handler=new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            switch (msg.what){                case URL_CONNECT:                    String message=msg.obj.toString();                    textView.setText(message);                    break;                default:                    break;            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button_connection= (Button) findViewById(R.id.button_connection);        button_connection.setOnClickListener(this);        textView= (TextView) findViewById(R.id.textview);    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.button_connection:                //新开线程                new Thread(){                    @Override                    public void run() {                        connectServerlet();                    }                };                break;            default:                break;        }    }    private void connectServerlet() {        try {            //生成url对象            URL url = new URL("http://www.360.com");            //通过url的openConnection()方法得到URLConnection对象            URLConnection connection=url.openConnection();            //getInputStream()方法获取输入流            InputStream is=connection.getInputStream();            BufferedReader br=new BufferedReader(new InputStreamReader(is));            String line=br.readLine();            StringBuffer buffer=new StringBuffer();            while (line!=null){                buffer.append(line);                line=br.readLine();            }            //通过handler传递信息            Message msg=handler.obtainMessage();            msg.what=URL_CONNECT;            msg.obj=buffer.toString().trim();            handler.sendMessage(msg);            br.close();            is.close();        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}
0 0
原创粉丝点击