HttpURLConnection学习

介绍

HttpURLConnection类是位于java.net包下继承了URLConnection类的一个抽象类,每个 HttpURLConnection 实例都用于发出单个请求。

URL

HttpURLConnection的使用需要依赖URL类,URL类位于java.net包下,有很多种构造方法。

HttpURLConnection

设置网络权限

在AndroidManifest.xml文件的添加<manifest>标签下<uses-permission android:name="android.permission.INTERNET" />
允许通过HTTP访问网络资源

通过修改 AndroidManifest.xml 文件来临时允许明文 HTTP 流量。

可以测试http://www.httpbin.org/get这个网站

测百度https://www.baidu.com/

xml 复制代码
<application
    android:usesCleartextTraffic="true"
    ... >
    ...
</application>

GET 请求

java 复制代码
Button GET = findViewById(R.id.button);
GET.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 指定url
                    String url_baidu = "https://www.baidu.com/";
                    // 创建url对象
                    URL url = new URL(url_baidu);
                    // 创建连接对象
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // 设置请求方式
                    connection.setRequestMethod("GET");
                    // 建立连接,不发送数据
                    connection.connect();
                    // 获取响应码
                    int responseCode = connection.getResponseCode();
                    if(responseCode == HttpURLConnection.HTTP_OK) {
                        InputStream inputStream = connection.getInputStream();
                        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                        String inputLine;
                        StringBuilder content = new StringBuilder();
                        while ((inputLine = in.readLine()) != null) {
                            content.append(inputLine);
                        }
                        // 关闭流
                        in.close();
                        
                        // 更新UI,必须在主线程
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("Response:", content.toString());
                                // 你也可以用Toast显示结果
                                // Toast.makeText(getApplicationContext(), content.toString(), Toast.LENGTH_LONG).show();
                            }
                        });
                    } else {
                        Log.d("Response:", "Request failed with code: " + responseCode);
                    }
                    connection.disconnect();
                } catch (Exception e) {
                    // 记录异常
                    Log.e("Error", "Exception: " + e.getMessage(), e);
                }
            }
        }).start();
    }
});

POST请求

java 复制代码
        Button POST = findViewById(R.id.button2);
        POST.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url_example = "https://www.httpbin.org/forms/post";
                            URL url = new URL(url_example);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("POST");
                            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                            connection.setDoOutput(true);
                            connection.setDoInput(true);

                            String postData = "comments=555&custemail=111@111&custname=111&custtel=111&delivery=&size=small&topping=cheese&topping=onion";

                            OutputStream outputStream = connection.getOutputStream();
                            outputStream.write(postData.getBytes(StandardCharsets.UTF_8));
                            outputStream.flush();
                            outputStream.close();

                            int responseCode = connection.getResponseCode();
                            if(responseCode==HttpURLConnection.HTTP_OK){
                                InputStream inputStream = connection.getInputStream();
                                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                                String inputLine;
                                StringBuilder content = new StringBuilder();
                                while ((inputLine=in.readLine())!=null){
                                    content.append(inputLine);
                                }
                                in.close();

                                Log.d("Response",content.toString());

                            }
                            else{
                                Log.d("Response:","Request failed with code: " + responseCode);
                            }

                            connection.connect();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
            }
        });
相关推荐
髩獹朲小怪兽15 分钟前
学习鸿蒙Next 之路 http
学习·http·harmonyos
千殃sama34 分钟前
Flythings学习(一)基础
学习·flythings
PaLu-LI1 小时前
ORB-SLAM2之OpenCV reshape函数
开发语言·c++·opencv·学习·ubuntu
王俊山IT1 小时前
C++学习笔记----9、发现继承的技巧(一)---- 使用继承构建类(4)
开发语言·c++·笔记·学习
IOT.FIVE.NO.12 小时前
Linux学习笔记9 文件系统的基础
linux·笔记·学习
yingchenwy2 小时前
Mongodb学习记录
数据库·学习·mongodb
萱仔学习自我记录3 小时前
如何在 Jupyter Notebook 执行和学习 SQL 语句(中)—— 2、SQL基础数据类型
sql·学习·jupyter
wang_book3 小时前
uniapp学习(004-2 组件 Part.2生命周期)
前端·学习·微信小程序·小程序·前端框架·uni-app·vue
晚睡早起₍˄·͈༝·͈˄*₎◞ ̑̑3 小时前
苍穹外卖学习笔记(二十三)
java·开发语言·windows·笔记·学习·sprint
丶Darling.4 小时前
施磊C++ | 进阶学习笔记 | 5.设计模式
c++·笔记·学习·设计模式