欢迎访问我的个人博客,一起学习交流。^_^

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");

更多相关文章

  1. 浅谈Java中Collections.sort对List排序的两种方法
  2. mybatisplus的坑 insert标签insert into select无参数问题的解决
  3. python起点网月票榜字体反爬案例
  4. Python list sort方法的具体使用
  5. python list.sort()根据多个关键字排序的方法实现
  6. android,service实例,播放音乐
  7. Android(安卓)调用.NET webservice
  8. android 加密数据库
  9. Android(安卓)单元测试

随机推荐

  1. Android(安卓)Log系统介绍 (基于Android(
  2. android根据姓名首字母字符顺序读取通信
  3. Android 基础总结:(三)Activity
  4. Android-support-v4源码查看
  5. Android Studio 里搭建自动化测试框架Rob
  6. android获取textview的行数
  7. Android 调整屏幕分辩率
  8. Android禁止EditText自动弹出软键盘的方
  9. Android sql数据库的Android包里面的函数
  10. Android(安卓)6.0只是增量更新? 看看新功