客户端POST发送json数据给服务端,客户端端接收服务器端json数据响应

客户端POST发送json数据给服务端

//请求的地址
        String url = "http://localhost:8080/springmvc/request/postRequest";
        //创建Http Request(内部使用HttpURLConnection)
        ClientHttpRequest request = 
            new SimpleClientHttpRequestFactory().   
                createRequest(new URI(url), HttpMethod.POST);
        //设置请求头的内容类型头和内容编码(GBK)
        request.getHeaders().set("Content-Type", "application/json;charset=gbk");
        //以GBK编码写出请求内容体
        String jsonData = "{\"username\":\"admin\", \"password\":\"admin\"}";
        request.getBody().write(jsonData.getBytes("gbk"));
        //发送请求并得到响应
        ClientHttpResponse response = request.execute();
        System.out.println(response.getStatusCode());


客户端接收服务器端json数据响应

  public static void jsonRequest() throws IOException, URISyntaxException {
        //请求的地址
        String url = "http://localhost:8080/springmvc/response/reponseContent";
        //创建Http Request(内部使用HttpURLConnection)
        ClientHttpRequest request = 
            new SimpleClientHttpRequestFactory().   
                createRequest(new URI(url), HttpMethod.POST);
        //设置客户端可接受的媒体类型
        request.getHeaders().set("Accept", "application/json");        
        //发送请求并得到响应
        ClientHttpResponse response = request.execute();
        //得到响应体的编码方式
        Charset charset = response.getHeaders().getContentType().getCharSet();        
        //得到响应体的内容        
        InputStream is = response.getBody();
        byte bytes[] = new byte[(int)response.getHeaders().getContentLength()];
        is.read(bytes);
        String jsonData = new String(bytes, charset);
        System.out.println("charset : " + charset + ", json data : " + jsonData);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值