Java代码中Post提交数据为JSON格式

这里调用的是微信检测是否违规文字,因为头部需要带上token参数,然后还需要JSON格式的数据

public static void main(String[] args){
	private static final String MSG_SEC_CHECK = "需要请求的接口URL?参数=%s";
	Map<String, Object> map = new HashMap<>(1);
        map.put("content", msg);
        // 替换 url 中的 %s 按顺序替换
        String format = String.format(MSG_SEC_CHECK, token);
        StringBuffer sb = new StringBuffer();
        // 转换为JSONobject对象 可以使用阿里的JSON工具包
        JSONObject json= JSONUtil.parseObj(map);
        // 出于好奇打印了转换后的对象 格式为: {"键":"值"}
        log.info("------map{}", jsonObject1);
        try {
            URL url = new URL(format);
            //创建httpsclient对象 还可以创建httpclient对象
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            //  Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
            byte[] data = (json.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");
            // 开始连接请求
            conn.connect();
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // 写入请求的字符串
            out.write((json.toString()).getBytes());
            out.flush();
            out.close();
            // 请求的状态码
            //System.out.println(conn.getResponseCode());
            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in1 = conn.getInputStream();
                try {
                    String readLine;
                    // 读数据
                    BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, StandardCharsets.UTF_8));
                    while ((readLine = responseReader.readLine()) != null) {
                        sb.append(readLine).append("\n");
                        log.info("------拼接中{}", sb);
                    }
                    // 拼接后的最终结果
                    //System.out.println(sb);
                    // 关流
                    responseReader.close();

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else {
                System.out.println("error++");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将拼接好的字符串转换为JSONobject 便于取值
        JSONObject jsonObject2 = JSONUtil.parseObj(sb);
     	// 获取到状态码返回结果
        return jsonObject2.getInt(CODE);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
如果POST请求提交参数JSON格式,可以通过以下步骤在Java Servlet获取: 1. 在Servlet的doPost方法,通过HttpServletRequest对象获取POST请求JSON格式参数,并将参数转化为Java对象,示例代码如下: ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取POST请求JSON格式参数 BufferedReader reader = request.getReader(); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } String jsonString = sb.toString(); // 将参数转化为Java对象 ObjectMapper objectMapper = new ObjectMapper(); MyParam myParam = objectMapper.readValue(jsonString, MyParam.class); // ... } ``` 在上面的示例,通过request.getReader()方法获取POST请求的字符流,然后将字符流转化为JSON格式字符串。接着,使用Jackson库的ObjectMapper类将JSON格式字符串转化为Java对象。 2. 在前端页面,使用Ajax向Servlet提交POST请求,并传递JSON格式参数,示例代码如下: ``` var myParam = { "param1": "value1", "param2": "value2" }; $.ajax({ type: "POST", url: "/servlet/MyServlet", contentType: "application/json", data: JSON.stringify(myParam), success: function(data) { // ... } }); ``` 在上面的示例,通过contentType属性指定请求数据类型为JSON格式,使用JSON.stringify方法将JavaScript对象转化为JSON格式字符串,然后将JSON格式字符串作为请求参数传递给Servlet。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

springcloud+dubbo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值