java-HttpURLConnection 发送POST请求 传递参数或JSON数据

2023-05-16

java-HttpURLConnection 发送POST请求 传递参数或JSON数据

需求 三方接口   restful请求  POST方式   参数JSON   接收数据JSON

HttpURLConnection发送POST请求

public class RestUtil {

    public String postMethod(String url,String param){
        // 结果值
        StringBuffer rest=new StringBuffer();

        HttpURLConnection conn=null;
        OutputStream out=null;
        BufferedReader br=null;

        try {
            // 创建 URL
            URL restUrl = new URL(url);
            // 打开连接
            conn= (HttpURLConnection) restUrl.openConnection();
            // 设置请求方式为 POST
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection","keep-Alive");
            // 设置接收文件类型
//            conn.setRequestProperty("Accept","application/json");
            //设置发送文件类型
            /**
			 这里注意  传递JSON数据的话 就要设置
			 普通参数的话 就要注释掉
			 */
            conn.setRequestProperty("Content-Type","application/json");
            // 输入 输出 都打开
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //开始连接
            conn.connect();

            // 传递参数  流的方式
            out=conn.getOutputStream();
            out.write(param.getBytes());
            out.flush();

            // 读取数据
            br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line=null;
            while (null != (line=br.readLine())){
                rest.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭所有通道
            try {
                if (br!=null) {
                    br.close();
                }
                if (out!=null) {
                    out.close();
                }
                if (conn!=null) {
                    conn.disconnect();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return rest.toString();
    }
}

客户端请求

 @GetMapping("/getData")
    public String getData() {

        RestUtil restUtil = new RestUtil();

        String IP = "127.0.0.1";
        String url = "http://" + IP + "/server/data";
        String level = "0";
        String dateTime = "2020-10";
        // 参数
        String param;
        // 接收数据
        String result;
        /**
         * 第一种   参数为JSON
         * 要打开设置 conn.setRequestProperty("Content-Type","application/json");
         */

        param = "{\"level\":\"" + level + "\",\"dateTime\":\"" + dateTime + "\"}";
        result = restUtil.postMethod(url, param);

        /**
         * 第二种  直接传递参数
         * 关闭 conn.setRequestProperty("Content-Type","application/json");
         */
        StringBuffer dataBuffer = new StringBuffer();
        try {
            dataBuffer.append(URLEncoder.encode("level", "UTF-8"));
            dataBuffer.append("=");
            dataBuffer.append(URLEncoder.encode(level, "UTF-8"));

            dataBuffer.append("&");

            dataBuffer.append(URLEncoder.encode("dateTime", "UTF-8"));
            dataBuffer.append("=");
            dataBuffer.append(URLEncoder.encode(dateTime, "UTF-8"));

            param = dataBuffer.toString();

            result = restUtil.postMethod(url, param);

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

        //接收的数据
        System.out.println("result==" + result);

        // 然后对 数据 进行 JSON解析
        JSONObject jsonObject = JSON.parseObject(result);

        String code = jsonObject.get("code") == null ? "" : jsonObject.get("code").toString();
        String message = jsonObject.get("message") == null ? "" : jsonObject.get("message").toString();
        dateTime = jsonObject.get("dateTime") == null ? "" : jsonObject.get("dateTime").toString();
        JSONArray dataJsonArray = (JSONArray) jsonObject.get("data");
        if (null != dataJsonArray && dataJsonArray.size() > 0) {
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject data = (JSONObject) dataJsonArray.get(i);
                String account = data.get("account") == null ? "" : data.get("account").toString();
                String name = data.get("name") == null ? "" : data.get("name").toString();

                System.out.println("code==" + code + "++message==" + message + "++dateTime==" + dateTime
                        + "++account==" + account + "++name==" + name);
            }
        }

        return "success";
    }

服务端 如果接收为JSON数据的话 就要从流中取出数据

(2021/6/21新增->不建议这种方法,直接参数加注解 @RequestBody)

	//读取流中的json数据
        BufferedReader br=null;
        StringBuffer result=null;
        try {
            br=new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
            String line=null;
            while (null!=(line=br.readLine())){
                result.append(line);
            }
            System.out.println("接收参数:"+result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

服务端 如果是普通参数的话 直接获取

		 /**
         * 如果是参数的方式
         */
        String level = request.getParameter("level");
        String dateTime = request.getParameter("dateTime");

服务端返回JSON数据

		return "{\"code\":\"100001\",\"message\":\"请求成功\",\"dateTime\":\"2020-10\"," +
                "\"data\":[{\"account\":\"zhangsan\",\"name\":\"张三\"}," +
                "{\"account\":\"lisi\",\"name\":\"李四\"}," +
                "{\"account\":\"wangwu\",\"name\":\"王五\"}," +
                "{\"account\":\"xiaoliu\",\"name\":\"小六\"}]}";

推荐使用第三方库

这里使用的是 hutool , 很方便

		 public static void main(String[] args) {
        // hutool
        // get 请求
        String getRequestStringUrl = "http://localhost:8080/getRequest?id=1";
        HttpRequest.get(getRequestStringUrl).timeout(5 * 60 * 1000).execute();

        // post 请求 传递json参数
        String postRequestStringUrl = "http://localhost:8080/postRequest";
        // 参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data","123");
        jsonObject.put("email","123456@163.com");
        // 设置请求头
        Map<String, String > heads = new HashMap<>();
        heads.put("Content-Type", "application/json;charset=UTF-8");
        // 纯请求  要结果的话 最后加 .body()
        HttpRequest.post(postRequestStringUrl) // url
                .headerMap(heads, false) // 请求头设置
                .body(jsonObject.toJSONString()) // json参数
                .timeout(5 * 60 * 1000) // 超时
                .execute(); // 请求
                // .body(); // 返回值
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java-HttpURLConnection 发送POST请求 传递参数或JSON数据 的相关文章

随机推荐