java向指定地址url发post请求,并携带json格式参数

先定义我们的工具类

 public static String sendPost(String url, String jsonData) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            URLConnection con = realUrl.openConnection();
            HttpURLConnection conn = (HttpURLConnection) con;
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type",
                    "application/json"); // 设置内容类型
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(
                    conn.getOutputStream(), "utf-8"));
            out.write(jsonData);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            byte[] bresult = result.toString().getBytes();
            result = new StringBuilder(new String(bresult, "utf-8"));
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

接受方务必要加如下注解

@RequestBody 

该注解的作用:@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,您可以使用 Java 的 HttpURLConnection 类来送带有 header 和 JSON 参数请求。以下是一个示例代码: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUrlConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api/endpoint"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为 POST connection.setRequestMethod("POST"); // 设置请求头部 connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", "Bearer your_token_here"); // 设置可写入请求数据 connection.setDoOutput(true); // 构建 JSON 请求数据 String jsonData = "{\"name\":\"John Smith\",\"email\":\"john.smith@example.com\"}"; // 写入请求数据 DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(jsonData); outputStream.flush(); outputStream.close(); // 获取响应数据 int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); // 输出响应数据 System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们首先创建了一个 URL 对象,并使用它创建了一个 HttpURLConnection 对象。接下来,我们设置了请求方法为 POST,并设置了请求头部,包括 Content-Type、Accept 和 Authorization。然后,我们设置了可写入请求数据,并将 JSON 数据写入请求输出流。最后,我们获取响应数据并输出它。请注意,这只是一个示例代码,您需要将 URL请求头部和 JSON 数据替换为您自己的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值