java-http携带json参数访问接口

一个接收map的接口

 @RequestMapping("kkw")
    public String kkw(@RequestBody Map<String,Object>map){
        if(map != null){
            System.out.println(JSONObject.toJSONString(map));;
        }
        return "success";
    }

package com.example.demo.test;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class HttpJsonCase {
    public static void main(String[] args) {
        try {
            // 定义目标 URL
            String url = "http://127.0.0.1:9200/kkw";

            // 创建 HTTP 连接并设置请求方法为 POST
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");

            // 设定要传输的数据格式为 JSON
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");

            // 启用输出,因为我们需要将 JSON 请求正文发送到 API 端点。
            conn.setDoOutput(true);

            Map<String,Object> map = new HashMap<>();
            map.put("key","value");
            map.put("name","caoxuekun");

            // 创建 JSON 数据对象
            String jsonInputString = JSONObject.toJSONString(map);

            // 将 JSON 数据写入 HTTP 请求正文中
            try {
                OutputStream os = conn.getOutputStream();

                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }catch (Exception e){

            }

            // 获取 API 响应并打印
            try{
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());
            }catch (Exception e){
                e.printStackTrace();
            }

            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

posted on 2023-06-20 23:07  x-cuke  阅读(430)  评论(0)    收藏  举报