java代码实现post json数据到springmvc中并获取http请求的内容

需求:不使用浏览器进行访问,而是希望使用GroboUtils-5进行多线程测试http post json数据的测试(使用GroboUtils-5进行多线程测试参考:使用GroboUtils多线程并发请求测试springmvc controller

 

这个需求带来两个问题:1是如何使用java.net下的API实现向springmvc post json数据;2是在访问springmvc如何显示这些数据,以方便我们看到post的数据是否正确。

解决方案:

直接上代码

对于问题1:

public class BellyJsonPoster {

    private URL url;

    public BellyJsonPoster(URL url) {
        if (!url.getProtocol().toLowerCase().startsWith("http")) {
            throw new IllegalArgumentException(
                    "Posting only works for http URLs");
        }
        this.url = url;
    }

    public InputStream post() throws IOException {

        // open the connection and prepare it to POST
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //设置http连接属性

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST"); // 可以根据需要 提交 GET、POST、DELETE、INPUT等http提供的功能
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);

        //设置http头 消息
		//设定 请求格式 json,也可以设定xml格式的
        connection.setRequestProperty("Content-Type", "application/json");  
		//设定 请求格式 xml,
        //connection.setRequestProperty("Content-Type", "text/xml");
		//设定响应的信息的格式为 json,也可以设定xml格式的		
        connection.setRequestProperty("Accept", "application/json");
		//特定http服务器需要的信息,根据服务器所需要求添加
		//connection.setRequestProperty("X-Auth-Token","xx");  

        //添加 请求内容
        JSONObject user = new JSONObject();
        user.put("id", "1");
        user.put("name", "bellychang");
        user.put("pwd", "123");

        try (OutputStreamWriter out
                     = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {

            // The POST line, the Content-type header,
            // and the Content-length headers are sent by the URLConnection.
            // We just need to send the data
            out.write(user.toString());            
            out.flush();
        }

        // Return the response
        return connection.getInputStream();
    }
}

 

对于问题2:写了一个工具类来实现,这样在Contorller中调用这个方法就可以显示Header和body的内容

 

public class BellyWebUtil {

    public static void readHttpHeaders(HttpServletRequest request) {
        Enumeration headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                System.out.println(headerNames.nextElement().toString() + ":" + request.getHeader(headerNames
                        .nextElement().toString()));
            }
        }
    }

    public static void readHttpBody(HttpServletRequest request) throws IOException {

        //读取input流
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream(),
                "utf-8"));
        StringBuffer sb = new StringBuffer("");
        String temp;
        while ((temp = br.readLine()) != null) {
            sb.append(temp);
        }
        br.close();
        System.out.println(sb.toString());
    }

    public static void readHttpRequest(HttpServletRequest request) throws IOException {
        readHttpHeaders(request);
        readHttpBody(request);
    }
}

参考:
java 发送 json、xml格式的 http请求,并读取响应response内容实例
java接收http请求body中的json数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值