想要使用HTTP协议的GET与POST方法首先需要执行一下两个步骤。

1.新建xml文件夹,在此目录下创建网络配置文件:network-security-config.xml

android调用浏览器打开url地址 安卓手机打开url教程_数据

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true"/>
</network-security-config>

2.然后需要在AndroidManifest.xml中申请权限,并在<application>中使用刚刚创建好的网络安全配置文件。

Google为保证用户数据和设备的安全,针对下一代 Android 9.0系统(Android P) 的应用程序,将要求默认使用加密连接,这意味着 Android P 将禁止 App 使用所有未加密的连接,因此运行 Android P 系统的安卓设备无论是接收或者发送流量,未来都不能明码传输,需要使用下一代(Transport Layer Security)传输层安全协议,而 Android Nougat 和 Oreo 则不受影响。

<uses-permission android:name="android.permission.INTERNET"/>
 <application
android:networkSecurityConfig="@xml/network_security_config">

3.GET请求代码配置

private void getHttp() {
    //因为网络请求是耗时操作,所以需要创建一个子线程来运行,避免主UI线程卡死
    new Thread(){
        @Override
        public void run() {
            try {
                //HttpURLConnection
                //1.实例化一个URL对象
                URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1");

                //2.获取HttpURLConnection实例
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                //3.设置和请求相关的属性
                //请求方式
                connection.setRequestMethod("GET");
                //请求超时时长 ms
                connection.setConnectTimeout(6000);

                //4.获取响应码
                // 200:成功/404:未请求到指定资源/500:服务器异常
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    //5.判断响应码并获取响应数据(响应的正文)
                    //获取响应的流
                    InputStream is = connection.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    // bis.read(b); 该方法返回值是int类型数据,代表的是实际读到的数据长度
                    byte[] b = new byte[1024];
                    int len = 0;
                    //在循环中读取输入流
                    while( (len = bis.read(b)) != -1) {
                        //将字节数组里面的内容存/写入缓存流
                        //参数1:待写入的数组
                        //参数2:起点
                        //参数3:长度
                        baos.write(b, 0, len);
                    }
                    //关闭资源
                    baos.flush();
                    bis.close();
                    baos.close();

                    //6.输出获取到到数据
                    String msg = new String(baos.toByteArray());
                    Log.d("MainActivity", msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }.start();
}

运行结果如下:

D/MainActivity: {"status":1,"data":{"title":"Tony\u8001\u5e08\u804ashell\u201....

Tips:若程序在获取响应请求时出现:java.net.SocketException: socket failed: EPERM (Operation not permitted)
这只需要确认在Manifest.xml文件申请权限网络权限后,卸载软件再重装就好了。

4.POST请求代码配置

private void postHttp() {
    //因为网络请求是耗时操作,所以需要创建一个子线程来运行
    //避免主UI线程卡死
    new Thread(){
        @Override
        public void run() {
            try {
                //HttpURLConnection
                //1.实例化一个URL对象
                URL url = new URL("http://www.imooc.com/api/okhttp/postmethod");

                //2.获取HttpURLConnection实例
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                //3.设置和请求相关的属性
                //请求方式
                connection.setRequestMethod("POST");
                //请求超时时长 ms
                connection.setConnectTimeout(6000);
                //设置允许输出
                connection.setDoOutput(true);
                //设置请求数据的类型
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                //获取输出流(请求的正文)
                OutputStream os = connection.getOutputStream();
                os.write(("account=" + "David" + "&pwd=" + "123456").getBytes());

                //4.获取响应码
                // 200:成功/404:未请求到指定资源/500:服务器异常
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    //5.判断响应码并获取响应数据(响应的正文)
                    //获取响应的流
                    InputStream is = connection.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    // bis.read(b); 该方法返回值是int类型数据,代表的是实际读到的数据长度
                    byte[] b = new byte[1024];
                    int len = 0;
                    //在循环中读取输入流
                    while( (len = bis.read(b)) != -1) {
                        //将字节数组里面的内容存/写入缓存流
                        //参数1:待写入的数组
                        //参数2:起点
                        //参数3:长度
                        baos.write(b, 0, len);
                    }
                    //关闭资源
                    baos.flush();
                    bis.close();
                    baos.close();

                    //6.输出获取到到数据
                    String msg = new String(baos.toByteArray());
                    Log.d("MainActivity", msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }.start();
}

运行结果:

D/MainActivity: {"errorCode":1,"data":{"ip":"42.122.32.10","headers":{"Accept-Encoding":"gzip","User-Agent"...
其中:
设置请求数据的类型
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
"Content-Type":"application\/x-www-form-urlencoded"
输出流输出的内容
os.write(("account=" + "David" + "&pwd=" + "123456").getBytes());
"params":"account=David&pwd=123456"

android调用浏览器打开url地址 安卓手机打开url教程_java_02


5.使用GET获取网络图片:

private void getHttpPic(final Handler handler, final String path) {
    new Thread(){
        @Override
        public void run() {
            try {
                URL url = new URL(path);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(6000);

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    InputStream is = connection.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    byte[] b = new byte[1024];
                    int len = 0;
                    Bitmap bitmap = null;
                    while( (len = bis.read(b)) != -1) {
                        baos.write(b, 0, len);
                    }
					
					//使用BitmapFactory将字节转换成图片内容
                    //Bitmap bitmap = BitmapFactory.decodeStream(bis);
                    bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);

					baos.flush();
					baos.close();
                    bis.close();
                    is.close();
					
					//将图片信息交给Handler处理
                    Message message = new Message();
                    message.what = 1;
                    message.obj = bitmap;
                    handler.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }.start();
}