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");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了使用HttpURLConnection来发送和接收HTTP请求和响应,您需要按照以下步骤操作: 1. 创建HttpURLConnection对象,并将其连接到URL对象。例如: URL url = new URL("http://www.example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 2. 设置请求方法和连接属性,如连接超时和读取超时。例如: conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); 3. 添加请求头(可选)。例如: conn.setRequestProperty("User-Agent", "Android"); conn.setRequestProperty("Content-Type", "application/json"); 4. 如果POST请求,添加请求体。例如: String requestBody = "{\"username\":\"user123\",\"password\":\"pass123\"}"; OutputStream outputStream = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); 5. 发送请求,获取响应码和响应数据。例如: int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder responseData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { responseData.append(line); } reader.close(); inputStream.close(); String responseString = responseData.toString(); } 以上是使用HttpURLConnection发送和接收HTTP请求和响应的基本步骤。具体实现需根据具体的业务需求和网络情况进行调整和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值