HttpURLConnection

HttpURLConnection

1.简介

首先我们看一下JDK文档对这个类的描述:

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time. 

大致的意思是:

每个HttpURLConnection实例用于单个的网络请求,但是底层的HTTP服务器可以透明的共享其他实例。在调用HttpURLConnection实例的InputStream()或OutputStream()方法获取相应的网络资源后应该调用InputStream或OutputStream实例的close()方法关闭输入输出流,释放资源,但是不会影响任何共享的HttpURLConnection持久连接。调用HttpURLConnection实例的disconne()方法可以关闭HttpURLConnection,从而关闭底层闲置的socket。

到此我们对HttpURLConnection有了一个大致的了解,我们不关心底层如何实现Http的连接,三次握手等等,只关心访问的地址,请求格式、响应头,连接、读取数据的超时,获取网络资源,及输入输出流的释放等等。

2.常用的方法

1、setRequestMethod(String method)
此方法用于设置HTTP请求方式,如POST,GET,PUT,DELETE,HEAD等等,注意要是大写的string,如String method = "POST"
2、etRequestProperty(String key,String value)
此方法主要是设置HttpURLConnection请求头里面的属性比如Cookie、User-Agent(浏览器类型)、Content-Type等等,具体可以看HTTP头相关的材料至于要设置什么这个要看服务器端的约定
3、setDoInput(boolean doInput)
此方法用于设置是否开启允许输入,即请求的服务器能否向我们的HttpURLConnection写入资源,设置为true,才可使用HttpURLConnection实例的getInputStream().read()方法读取请求的服务器写入HttpURLConnection的资源。 
4、setDoOutput(boolean doOutput)
此方法用于设置是否开启允许输出,即我们的HttpURLConnection能否向请求的服务器写入资源,设置为true,才可使用HttpURLConnection实例的getOutputStream().write() 向访问的服务器写入资源。
5、setConnectTimeout(int timeOut)
此方法用于设置HTTP连接的超时时间,单位是毫秒,如果到了设置的连接超时时间而HTTP还未连接上要访问的服务器,则HttpURLConnection会放弃连接,从而不会导致此请求一直堵塞。
6、setReadTimeout(int timeOut)
此方法用于设置向服务器读取资源时时间,单位是毫秒,如果到设置的超市时间还未读取完数据的话,HttpURLConnection则会放弃读取,从而不会导致此请求一直堵塞。
7、setUseCaches(boolean useCaches)
此方法用于设置是否使用缓存,一般的网络请求设置为false。
8、connect()
此方法在设置完属性执行,进行HTTP连接。
9、getOutputStream()
此方法用于获取输出流,即HttpURLConnection向服务器写数据的写入流。
10、getInputStream()
此方法用于获取输入流,即服务器向HttpURLConnection写数据的写入流。
11、disconnect()
此方法用于关闭HttpURLConnection连接。

3.使用步骤

获取URL->打开HttpURLConnection->设置连接属性->写入或者写出数据->释放资源->关闭HttpURLConnection

4.详细代码

自己封装的HttpURLConnction一个网络请求方法。
代码如下:

/**
     * http访问
     * @param urlStr 访问的url
     * @param requestJson 参数json格式的String
     * @param method post,get,etc
     * @return
     * @throws IOException
     */
    public static String httpConnect(String urlStr, String requestJson,String method)  {
        //建立连接
        StringBuffer buffer;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection)url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(method);
            conn.setConnectTimeout(5000);//5秒连接超时时间
            conn.setReadTimeout(5000);//5秒读取超时时间
            conn.setRequestProperty("Content-Type", "application/json"); //指定格式为json
            conn.connect();


            if(null != requestJson){
                OutputStream outputStream = conn.getOutputStream();
                //注意编码格式
                outputStream.write(requestJson.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
            }
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            buffer = new StringBuffer();
            while ((str = bufferedReader.readLine())!=null) {
                buffer.append(str);
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            //释放资源
            try {
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
                if (null != inputStreamReader) {
                    inputStreamReader.close();
                }
                if(null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (null!=conn) {
                conn.disconnect();
            }
        }
        Log.e("Back json", buffer.toString());
        return buffer.toString();
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值