Android——HttpUrlConnection

1. 开发者文档 API

A URLConnection with support for HTTP-specific features. See the spec for details.

Uses of this class follow a pattern:

  • Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  • Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  • Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by URLConnection.getOutputStream().
  • Read the response. Response headers typically include metadata such as the response body’s content type and length, modified dates and session cookies. The response body may be read from the stream returned by URLConnection.getInputStream(). If the response has no body, that method returns an empty stream.
  • Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

2. 解释一下

  • 通过调用URL.openConnection()并将结果转换为HttpURLConnection,可以获得一个新的HttpURLConnection。
  • 准备请求。请求的主要属性是其URI。请求头还可能包括元数据,如凭证、首选内容类型和会话cookie。
  • 可选地上载请求主体。如果实例包含请求体,则必须使用setDoOutput(true)配置实例。通过写入URLConnection.getOutputStream()返回的流来传输数据。
  • 读取响应。响应头通常包括元数据,如响应主体的内容类型和长度、修改日期和会话cookie。响应体可以从URLConnection.getInputStream()返回的流中读取。如果响应没有主体,则该方法返回一个空流。
  • 断开连接。一旦读取了响应体,应该通过调用disconnect()关闭HttpURLConnection。断开连接释放连接所持有的资源,以便它们可以被关闭或重用。

3. 实践

private void sendRequestWithHttpRulConnection(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder reponse = new StringBuilder();
                    String line;
                    while((line = reader.readLine()) != null){
                        reponse.append(line);
                    }
                    showResponse(reponse.toString());
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(reader != null){
                        try{
                            reader.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

首先需要获取到HttpUrlConnection 的实例,一般只需new出一个URL 对象,并传入目标的网络地址,然后调用一下 openConnection() 方法即可。

在得到了HttpUrlConnection实例后,我们可以设置一下HTTP请求所用的方法:GET和POST。GET表示希望从服务器那里获取数据,而POST则表示希望提交数据给服务器。

接下来就可以进行一些自由的定制了,比如设置连接超时、读取超时的毫秒数,以及服务器希望得到的一些消息头等。

之后再调用getInputStream() 方法就可以获取到服务器返回的数据了,剩下的任务就是对输入流进行读取。

最后调用disconnect() 方法将这个HTTP连接关闭掉。

如果使用POST方法,需设置connection.setDoOutput(true),再在获取输入流之前把要提交的数据写出即可,注意每条数据都要以键值对的形式存在,数据与数据之间用“&”符号隔开,for example:
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");

猜你喜欢

转载自blog.csdn.net/qq_35008279/article/details/82015286
今日推荐