Android使用HttpURLConnection发送网络请求(笔记)

首先发送请求得先拥有权限

android:name="android.permission.INTERNET" />
然后就是发送请求时,要另立线程发送请求,不然会闪退。

GET请求

private void getHttps() {
    try {
        //根据URL地址实例化一个URL对象,用于创建HttpURLConnection对象。
        URL url = new URL("http://v.juhe.cn/wz/citys?key=相应的KEY值");
        //openConnection获得当前URL的连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置3秒的响应超时
        conn.setConnectTimeout(3000);
        //设置允许输入
        conn.setDoInput(true);
        //设置为GET方式请求数据
        conn.setRequestMethod("GET");
        //获取连接响应码,200为成功,如果为其他,均表示有问题
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            //getInputStream获取服务端返回的数据流。
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = "";
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            Log.i("info", responseCode + "  响应文本:\n" + sb.toString());
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

POST请求:

/*
BODY体中包含一个请求数据
 */
    private void POSTHttp() throws Exception {
        //1. URL
        URL url = new URL("http://v.juhe.cn/wz/citys");
        //2. HttpURLConnection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置3秒的响应超时
        conn.setConnectTimeout(3000);
        //3. POST
        conn.setRequestMethod("POST");
        //设置请求报文头,设定请求数据类型
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //5. 使用输出流  传递请求参数
        conn.setDoOutput(true); //开启输出流
        OutputStream os = conn.getOutputStream();
        String param = "key=相对应的KEY值";
        os.write(param.getBytes("utf-8"));
        os.flush();
        //6.  发送请求获取输入流
        InputStream is = conn.getInputStream();
        //7. 解析is  获取响应文本
        String line = "";
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        Log.i("info", "post响应文本:\n" + sb.toString());
    }

/*
包含消息头的请求
 */
private void postHttp2() throws Exception{
    //1. URL
    URL url = new URL("http://api.neekin.com/OBD/getRecord.php");
    //2. HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //设置3秒的响应超时
    conn.setConnectTimeout(3000);
    //3. POST
    conn.setRequestMethod("POST");
    //设置请求报文头,设定请求数据类型
    //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Cookie","key=dae2c334e2a1451d0a1baaf452053779tH0pt7KstpYHtHYnYHjqJHJptsDpK7JqtpaqJHY1YH0GK7Y1YHwHtHBOYHwHt9YrYPDHY7YrYHjqJHY1YHDHY9YSYH5HY9YLYH5Ht7YLtpYHY7YoYHNHY7YSYHNHYsY1YHYHy9YLtpYHtsYHtsYHY9Yots05");
    //5. 使用输出流  传递请求参数
    conn.setDoOutput(true); //开启输出流
    OutputStream os = conn.getOutputStream();
    //设置BODY体中数据
    String param = "";
    os.write(param.getBytes("utf-8"));
    os.flush();
    //6.  发送请求获取输入流
    InputStream is = conn.getInputStream();
    //7. 解析is  获取响应文本
    String line = "";
    StringBuffer sb = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    Log.i("info", "post2---响应文本:\n" + sb.toString());
}

/*
请求体中有两个数据时
 */
    private void postHttp3() throws Exception{
        //1. URL
        URL url = new URL("http://api.neekin.com/OBD/getOilPrice.php");
        //2. HttpURLConnection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置3秒的响应超时
        conn.setConnectTimeout(3000);
        //3. POST
        conn.setRequestMethod("POST");
        //设置请求报文头,设定请求数据类型
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //5. 使用输出流  传递请求参数
        conn.setDoOutput(true); //开启输出流
        OutputStream os = conn.getOutputStream();
        //设置BODY体中数据
        String param = "city=白城"+"&"+"number=90";
        os.write(param.getBytes("utf-8"));
        os.flush();
        //6.  发送请求获取输入流
        InputStream is = conn.getInputStream();
        //7. 解析is  获取响应文本
        String line = "";
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        Log.i("info", "post3---响应文本:\n" + sb.toString());
    }


你可能感兴趣的:(Android使用HttpURLConnection发送网络请求(笔记))