java后台post请求发送json参数,并通过HttpServletRequest获取post请求中的body内容

一、java后台post请求发送json参数

GET请求向服务器发送的数据,都放在url中,这样在发送请求时不用向请求正文中写入数据。而POST请求在发送时,必须先将发送的数据,写入到请求正文中。

package dw.health;

import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class App
{
    public static JSONObject sendPost(String url,JSONObject jsonParam) throws Exception {
        OutputStream out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            // 创建url资源
            URL url_ = new URL(url);
            // 建立http连接
            conn = (HttpURLConnection) url_.openConnection();
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置允许输入、允许输出
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            // 转换为字节数组
            byte[] data = (jsonParam.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");
            // 开始连接请求
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream()) ;
            // 写入请求的字符串(此时jsonParam数据是放在了请求正文body里)
            out.write((jsonParam.toString()).getBytes());
            out.flush();
            out.close();
            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
                // System.out.println("连接成功");
                // 请求返回的数据
                InputStream in1 = conn.getInputStream();
                try {
                    String readLine=new String();
                    BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
                    while((readLine=responseReader.readLine())!=null){
                        result.append(readLine).append("\n");
                    }
                    responseReader.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else {
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }

        } catch (Exception e) {
                throw new Exception(e);
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }

        return JSONObject.parseObject(result.toString());
    }

    public static void main( String[] args ) throws Exception {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("para1", "para1");
       	jsonParam.put("para2", "para2");
		jsonParam.put("para3", "para3");
        String url="servlet请求地址";
        JSONObject data = sendPost(url,jsonParam);
        System.out.println(data);

    }

}

二、通过HttpServletRequest获取post请求中的body内容(未使用注解)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String str = "";
        String wholeStr = "";
        while((str = reader.readLine()) != null){
            wholeStr += str;
        }
        JSONObject param = JSONObject.parseObject(wholeStr);
        String para1 = param.getString("para1");
        String para2 = param.getString("para2");
        String para3 = param.getString("para3");
        JSONObject result = new JSONObject();
        PrintWriter writer = null;
        LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
        String resp = "";
        JSONObject jsonobj = new JSONObject(true);
        try {
            param.put("para4","para4");
            result = param;
            resp = result.getString("data");
        } catch (Exception e) {
            hm.put("errorcode", "1");
            hm.put("errortext", e.getMessage());
            jsonobj.putAll(hm);
            resp = jsonobj.toJSONString();
        }

        try {
            response.setCharacterEncoding("GBK");
            writer = response.getWriter();
            writer.write(resp);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 获取 POST 请求JSON 参数可以使用以下方法: 1. 使用 Servlet: 如果你在使用 Servlet 进行 Web 开发,可以通过以下代码获取 POST 请求JSON 参数: ```java import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line); } String jsonString = sb.toString(); // 在这处理 jsonString } } ``` 2. 使用 Spring MVC: 如果你在使用 Spring MVC 框架进行 Web 开发,可以通过以下代码获取 POST 请求JSON 参数: ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @PostMapping("/my-endpoint") public void handlePostRequest(@RequestBody String jsonString) { // 在这处理 jsonString } } ``` 以上代码,`jsonString` 变量即为 POST 请求JSON 参数。 请注意,在实际开发,你还需要进行一些参数校验、异常处理和逻辑处理等。以上代码仅提供了基本的获取 POST 请求 JSON 参数的方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值