HttpURLConnection

        在Android上发送HTTP请求一般有两种一种是HttpURLConnection,另一种是HttpClinet,由于httpClient存在API数量过多,扩展困难等缺点,不建议使用,并且在Android6.0系统中被移除。

        以下是介绍HttpURLConnection的使用方法。

private void sendRequestWithHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://www.baidu.com");//传入网络地址
                    httpURLConnection = (HttpURLConnection) url.openConnection();//
                    httpURLConnection.setRequestMethod("GET");//GET 获取数据
                    httpURLConnection.setConnectTimeout(8000);//链接超时时间
                    httpURLConnection.setReadTimeout(8000);//传递数据超时
                    InputStream inputStream = httpURLConnection.getInputStream();//获取数据流

                    //发送
//                    httpURLConnection.setRequestMethod("POST");
//                    DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
//                    dataOutputStream.writeBytes("usename=admin&pass=123");

                    //读取数据
                    reader = new BufferedReader(new InputStreamReader(inputStream));//
                    StringBuffer stringBuffer = new StringBuffer();
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        stringBuffer.append(line);
                    }
                    showResponse(stringBuffer.toString());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

新建一个子线程是因为获取网络数据属于耗时操作,所以需要在子线程中进行,

private void showResponse(final String toString) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            tv.setText(toString);
            Log.d("TAGT", "toString: " + toString);
        }
    });
}

通过runOnUiThread将子线程切换到主线程中去更新UI,Android不允许在子线程中更新UI 。

转发表明出处https://blog.csdn.net/qq_35698774/article/details/107307473

点击下载源码

android互助群:

感谢:郭霖的《第一行代码 第二版》

 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大不懂

码字不易,一块也是爱,么么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值