Android 中使用HttpUrlConnection实现get请求服务器

这篇文章主要演示:在android中如何向服务器发一个get请求,以及开子线程来更新ui,以及Handler发消息和处理消息的使用。

1.创建子线程请求数据:

final String strWebAddr = et_input.getText().toString();

new Thread(new Runnable() {
    @Override
    public void run() {
        try{
            URL url = new URL(strWebAddr);
            //获取一个连接
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置GET请求
            connection.setRequestMethod("GET");
            //设置超时时间
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(1000);

            //获取服务器响应码
            int ncode = connection.getResponseCode();
            if( ncode == 200 ){
                InputStream inputStream = connection.getInputStream();

                //将流转换成String
                String content = Utils.ReadStream(inputStream);

                //发消息
                Message msg = Message.obtain();
                msg.obj = content;
                handler.sendMessage(msg);
            }

        }catch(Exception e){
           e.printStackTrace();
        }
    }
});
这个ReadStream函数自己封装的:

public static String ReadStream(InputStream in) throws Exception{

    int len = -1;
    byte buffer[] = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    while ((len = in.read(buffer)) > 0 ){
        baos.write(buffer,0,len);
    }

    //关闭流
    in.close();

    String content = new String(baos.toByteArray());
    return content;
}

Handler的创建和使用():

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {

        String content = (String)msg.obj;
        tv_show.setText(content);

        super.handleMessage(msg);
    }
};


联网需要在清单文件中配置:



你可能感兴趣的:(Android区)