Http之HttpURLConnection

HttpURLConnection

Sun公司提供的库,也是Java的标准类库java.net中的一员,但这个类什么都没封装,用起来很原始,若需要高级功能,则会显得不太方便,比如重访问的自定义,会话和cookie等一些高级功能。

支持HTTPS协议,以流的形式进行上传和下载,配置超时时间,IPV6,连接池等功能。

用法(android):

get方法

 new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    Message message = new Message();
                    message.what = 2;
                    message.obj = response.toString();
                    handler.sendMessage(message);
                } catch (IOException ex) {
                    Log.e("s", "Error", ex);
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }

                }
            }
        }
        ).start();

设置权限 

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

post方法

 try {
            url = new URL("http://api.map.baidu.com/telematics/v3/weather?");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            printWriter.write("location=%E5%98%89%E5%85%B4");//post的参数 xx=xx&yy=yy
            printWriter.write("output=json");
            printWriter.write("ak=5slgyqGDENN7Sy7pw29IUvr");
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while((len=bis.read(arr))!= -1){
                bos.write(arr,0,len);
                bos.flush();
            }
            bos.close();
            Message message = new Message();
            message.what = 3;
            message.obj = bos.toString("utf-8").toString();
            handler.sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

谷歌在22版本之后不再支持HttpClient

因为兼容性问题,谷歌不愿意维护HttpClient,而使用HttpURLConnection
HttpURLConnection的API包小而简便,更适合安卓
HttpURLConnection能够提高速度和提升电池性能

又因为 HttpURLConnection 比较原始,所以一些第三方的框架应运而生,okhttp,retrofit,android-async-http,volley,他们的区别有时间抽空再回忆回忆

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpPost和HttpURLConnection是两种常用的HTTP请求方式,它们在实现上有一些区别和特点。 1. 功能和用途: - HttpPost是HttpClient库中的一个类,用于发送HTTP POST请求。它可以用来向服务器提交数据、上传文件等。 - HttpURLConnection是Java内置的HTTP客户端库,用于发送HTTP请求。它支持多种请求方式,包括GET、POST、PUT、DELETE等。 2. 依赖: - HttpPost需要通过引入HttpClient库来使用。 - HttpURLConnection是Java内置的库,无需额外引入。 3. 使用方式: - HttpPost使用相对简单,创建HttpPost对象后,可以设置请求头、请求体等参数,并使用HttpClient执行请求。 - HttpURLConnection使用起来略为复杂一些。需要先创建URL对象,然后通过openConnection方法获取HttpURLConnection对象,再设置请求方法、请求头、请求体等参数,并使用该对象进行连接和数据传输。 4. 性能和扩展性: - HttpPost借助HttpClient库,相对来说更加灵活和易于扩展。HttpClient提供了更多的功能和配置选项,并且支持连接池HTTPS等高级特性。 - HttpURLConnection是Java标准库的一部分,相对来说更加轻量级。它的功能相对简单,适合简单的HTTP请求场景。 综上所述,HttpPost和HttpURLConnection在功能和使用方式上有一些差异。HttpPost更适合于复杂的HTTP请求,而HttpURLConnection更适合于简单的HTTP请求。具体选择哪个取决于项目需求和开发者的偏好。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值