Android HttpURLConnection的简单使用

来源:互联网 发布:保利地产工资待遇知乎 编辑:程序博客网 时间:2024/06/07 20:24

HttpURLConnection的简单使用

使用网络操作时添加网络权限
<uses-permission android:name="android.permission.INTERNET" />

  • 获取HttpURLConnection实例
HttpURLConnection connection = null;try {    URL url = new URL("http://www.baidu.com");    connection = (HttpURLConnection) url.openConnection();} catch (Exception e) {    e.printStackTrace();}
  • 设置http请求所使用的方法
connection.setRequestMethod("GET")

GET 和 POST请求
GET请求一般用来从服务器获取数据,
而POST请求一般用来向服务器传入数据

  • 自由定制,比如apikey、连接超时等
connection.setConnectTimeout(8000);  //设置连接超时connection.setReadTimeout(8000);  //设置读取超时
  • 使用getInputStream()获取输入流,数据进行读取和处理
InputStream in = connection.getInputStream();
  • 获取输出流,并上传数据
DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.writeBytes("username=admin&password=123456789");
  • 最后关闭HTTP连接
connection.disconnect();

示例:

    private void sendRequestWithHttpURLConnection() {        // 开启线程来发起网络请求        new Thread(new Runnable() {            @Override            public void run() {                HttpURLConnection connection = null;                try {                    URL url = new URL("http://www.baidu.com");                    connection = (HttpURLConnection) url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(8000);                    connection.setReadTimeout(8000);                    InputStream inputStream = connection.getInputStream();                    // 对获取的输入流进行读取                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));                    StringBuilder response = new StringBuilder();                    String line;                    while ((line = reader.readLine()) != null) {                        response.append(line);  //添加到builder容器中                    }                    Message message = new Message();                    message.what = SHOW_RESPONSE;                    //将服务器返回的结果存放到Message中                    message.obj = response.toString();                    handler.handleMessage(message);                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                } catch (Exception e) {                    e.printStackTrace();                } finally {                    if (connection != null) {                        connection.disconnect();                    }                }            }        }).start();    }

参考:《第一行代码》

1 0
原创粉丝点击