http

1.什么是Http请求
Http请求是客户端和服务端之间发送请求和返回应答的标准(TCP)
客户端发出一个Http请求后就和服务器建立了TCP连接,服务端接受到请求并进行了处理后,返回给客户端相应数据。

2.什么是HTTPURLConnection
HTTPURLConnection是java的标准指定的网站发送GET请求,POST请求类,HTTPURLConnection继承自URLConnection可用与指定网站发送GET请求,post请求类,HTTPURLConnection在使用相对简单,并且易于推展,推荐使用。

3.如何使用HTTPURLConnection
创建URL对象
通过URL对象调用openConnection()方法获得HTTPURLConnection对象
HTTPURLConnection对象设置其他连接属性
HTTPURLConnection对象调用getinputstream()方法想服务器发送http请求并获取到服务器返回的输入流
获取输入流,转换成String字符串
注意:在Android中访问网络必须添加网络权限
在Android中访问网络必须放在子线程中(耗时操作)执行
使用HttpURLConnection获取请求
代码如下
`public class Main2Activity extends AppCompatActivity {
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    blid();


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    getweb();
                }
            }).start();
        }
    });
}

private void getweb() {


    try {

        URL url = new URL("https://www.csdn.net/");

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        Log.e("MAIN",httpURLConnection.getResponseCode()+"**************************");


        InputStream inputStream = httpURLConnection.getInputStream();

        InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");

        BufferedReader bufferedReader = new BufferedReader(reader);

        StringBuffer stringBuffer =new StringBuffer();

        String temp = null;


        while ((temp=bufferedReader.readLine())!=null){
            stringBuffer.append(temp);

        }

        bufferedReader.close();

        reader.close();

        inputStream.close();

        Log.e("MAIN",stringBuffer.toString());


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void blid() {
    button=findViewById(R.id.web_btn);
}

}
`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值