安卓——http网络请求——笔记

使用HttpURLConnection进行网络请求

网络请求通常需要在AndroidMainfest.xml中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

1、Get请求:获取服务器中的资源

//1、建立连接
HttpURLConnection httpURLConnection = null;//网络请求

            URL requestURL = new URL(url);
            httpURLConnection = (HttpURLConnection) requestURL.openConnection();//打开连接,已建立连接
            httpURLConnection.setRequestMethod("GET");//设置请求方式setRequestMethod()
            httpURLConnection.setConnectTimeout(5000);//设置连接超时时间    setConnectTimeout
          // httpURLConnection.setRequestProperty("Charset","utf-8");
            httpURLConnection.connect();//建立连接
    //如果请求==200,证明请求成功
           if(httpURLConnection.getResponseCode == 200){
            //2.获取数据获取二进制流的数据
            InputStream inputStream=httpURLConnection.getInputStream();//获取输入流,这个时候才真正发出HTTP请求
            BufferedReader reader=new BufferedReader((new InputStreamReader(inputStream)));//读取数据
          //3.从Bufferedreader中读取字符串
            String line;
            StringBuilder builder=new StringBuilder();
            while((line=reader.readLine()) != null){
                builder.append(line).append("\n");
            }
            reader.close();
            httpURLConnection.disconnect();
            if(builder.length()== 0){
                return  "null";
            }
            reader.close();
            httpURLConnection.disconnect();
}


            //4.在网络上读取到的数据
            result=builder.toString();

2、post :向服务器提交数据

   public String doPost() {
    //主线程不能进行网络请求,所以我们要开辟一个新的子线程来进行网络请求

    new Thread(new Runnable(){
        @Override
        public void run(){
            //1.建立连接
            try {
                URL url=new URL("http://XXXX.com");//登录云平台,注意这里可能会有异常,所以我们需要进行异常处理try catch
                HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();//打开一个HttpURLConnection连接
                //设置请求方法
                httpURLConnection.setRequestMethod("POST");
                //设置超时时间
                httpURLConnection.setConnectTimeout(1000);
                //设置从主机取读超时的时间
                httpURLConnection.setReadTimeout(1000);
                //2.注意因为登录云平台之间的数据格式是json,所以需要进行转
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("username","123456");
                jsonObject.put("Password","123456");
                String data=jsonObject.toString();
                //3.进行属性设置
                //将连接设置为长连接
                httpURLConnection.setRequestProperty("Connection","keep-alive");
                //设置待写入的数据为json
                httpURLConnection.setRequestProperty("Content-Type","application/json");
                //设置允许向链接写入数据,默认为false不允许
                httpURLConnection.setDoOutput(true);
                //设置允许从链接读取数据,默认为true 
                httpURLConnection.setDoInput(true);
                //4.写入数据
                //获得输出流向服务器提交数据
                OutputStream outputStream=httpURLConnection.getOutputStream();
                outputStream.write(data.getBytes());
                //对返回码进行判断,若==200,证明提交成功
                if(httpURLConnection.getResponseCode() == 200){
                    InputStream inputStream=httpURLConnection.getInputStream();//调用getInputStream后post请求才发送出去
                    //将字节流转换为字符类,再转换为缓冲字符流
                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
                    StringBuilder stringBuilder=new StringBuilder();
                    String str;
                    while ((str=bufferedReader.readLine())!=null){
                        stringBuilder.append(str);

                    }
                    result= stringBuilder.toString();
                    outputStream.close();
                    inputStream.close();
                    httpURLConnection.disconnect();

                }else{
                    Log.d("TAG","post请求失败");
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            //2.发送
        }
    }).start();

    return  result ;
}

设置为长连接和短链接的区别:

短链接:客户端和服务器每次进行操作,就建立一次连接,当任务结束就中断连接

长连接:在一个TCP连接上可以发送多个HTTP请求和接收多个HTTP响应。相比于短连接,长连接可以减少TCP连接的建立和关闭的开销,提高网络传输效率。当一个网页打开完成后,客户端和服务器之间用于传输HTTP数据的TCP连接不会关闭,客户端再次访问这个服务器时,会继续使用这一条已经建立的连接。Keep-Alive不会永久保持连接,它有一个保持时间。

在使用HTTPURLConnection进行长连接时,需要注意以下几点:

  1. 设置URLConnection的setDoOutput属性为true,表示可以向服务器发送数据,false 表示不可以,默认为false。
  2. 在发送完一个请求后,需要调用URLConnection的getInputStream方法获取响应数据,并读取完整个响应数据,以便复用连接。
  3. 在发送完所有请求后,需要调用URLConnection的disconnect方法关闭连接。
  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿ฅ( ̳• ε • ̳)ฅ

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值