手动发起get、post请求 -- HttpURLConnection

本文详细介绍了如何使用HttpURLConnection发起GET和POST请求,包括RequestParam和RequestBody两种传参方式,并提供了完整的代码示例。

前言

    现在对接接口数据,都有一些很好用的工具类,例如:RestTemplate,但有些场景还是需要我们自己手动去实现,而且自己实现一遍也有利我们理解。废话不多说了,现在通过HttpURLConnection来发起get、post请求。

Get请求

    @GetMapping("/getMethod")
    public String testGetMethod() {
        String result = "";
        String path = "http://127.0.0.1:8083/device/list?pageNo=1&pageSize=5&deviceType=IPC";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            conn.setRequestMethod(HttpMethod.GET.name());
            // 设置超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            int code = conn.getResponseCode();
            // 2xxx成功 3xxx重定向 4xxx资源错误 5xxx服务器错误
            if (code == 200) {
                InputStream is = conn.getInputStream();
                // 从输入流读取字符串,指定编码格式为UTF-8,不然会出现乱码的问题。
                result = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
            }

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

        return result;
    }

StreamUtils是Spring框架的一个数据流工具类,这边大家也可以自己实现,下面贴一下源码

	/**
	 * Copy the contents of the given InputStream into a String.
	 * Leaves the stream open when done.
	 * @param in the InputStream to copy from (may be {@code null} or empty)
	 * @return the String that has been copied to (possibly empty)
	 * @throws IOException in case of I/O errors
	 */
	public static String copyToString(@Nullable InputStream in, Charset charset) throws IOException {
		if (in == null) {
			return "";
		}

		StringBuilder out = new StringBuilder();
		InputStreamReader reader = new InputStreamReader(in, charset);
		char[] buffer = new char[BUFFER_SIZE];
		int bytesRead = -1;
		while ((bytesRead = reader.read(buffer)) != -1) {
			out.append(buffer, 0, bytesRead);
		}
		return out.toString();
	}

 

Post请求

post请求传参的时候一般有两种方式:RequestParamRequestBody

RequestParam

使用类似于get方式的key-value传参方式,Content-Type为application/x-www-form-urlencoded。

    @GetMapping("/postMethod")
    public String testPostMethod() {
        String result = "";
        String path = "http://127.0.0.1:8083/device/query";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            conn.setRequestMethod(HttpMethod.POST.name());
            // 设置传参方式,当服务端通过@RequestParam接受参数时,使用application/x-www-form-urlencoded
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            // 设置超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            String param = "pageNo=1&pageSize=5&deviceType=IPC";
            conn.setDoOutput(true);
            conn.getOutputStream().write(param.getBytes(Charset.forName("UTF-8")));

            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                // 从输入流读取字符串,指定编码格式为UTF-8,不然会出现乱码的问题。
                result = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

RequestBody

一般使用json格式传递参数,Content-Type为application/json。

    @GetMapping("/postJsonMethod")
    public String testPostJsonMethod() {
        String result = "";
        String path = "http://127.0.0.1:8083/device/create";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            conn.setRequestMethod(HttpMethod.POST.name());
            // 设置传参方式,当服务端通过@RequestBody接受参数时,使用application/json
            conn.setRequestProperty("Content-Type","application/json");
            // 设置超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            JSONObject param = new JSONObject();
            param.put("id", "0019318cac98402e83f3367102360777");
            param.put("deviceType", "IPC");
            param.put("name", "测试");
            param.put("gbid", "31011700041325005777");
            param.put("status", 1);
            param.put("latitude", 0.0);
            param.put("longitude", 0.0);
            conn.setDoOutput(true);
            conn.getOutputStream().write(param.toJSONString().getBytes(Charset.forName("UTF-8")));

            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                // 从输入流读取字符串,指定编码格式为UTF-8,不然会出现乱码的问题。
                result = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

 

注:读取数据的时候一定要指定编码格式为UTF-8,不然会出现乱码的问题。

 

 

内容概要:本文围绕可变桨叶四旋翼无人机的规范控制与点对点运动模拟展开,重点研究优化推力分配策略在翻转动作的应用与性能比较。通过Matlab代码实现,构建了四旋翼动力学模型,并设计了多种控制算法以实现精确的姿态调整与轨迹跟踪。研究对比了不同推力分配方案在执行高机动性翻转动作时的稳定性、能耗效率与响应速度,旨在提升无人机在复杂飞行任务的动态性能与控制精度。该仿真研究为无人机飞控系统的设计与优化提供了理论依据和技术支持。; 适合人群:具备一定自动控制理论基础和Matlab编程能力,从事无人机控制、飞行器动力学或机器人系统研究的科研人员及研究生。; 使用场景及目标:① 实现四旋翼无人机在三维空间的精确点对点运动控制;② 对比分析不同推力分配策略在执行翻转等高难度动作时的控制效果与能耗表现,优化飞行性能;③ 为无人机自主飞行、特技飞行及复杂环境下的机动控制提供算法验证平台。; 阅读建议:此资源以Matlab仿真为核心,建议读者结合相关控制理论知识,深入理解代码实现细节,重点关注动力学建模、控制律设计与推力分配模块。在学习过程,应动手调试参数,复现文翻转动作的仿真结果,并尝试拓展至其他复杂飞行任务,以加深对无人机控制机理的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值