直接取出 post 请求中的 json、得请求体参数、查看 post 请求参数

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。

方法如下:

       try{
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();

            StringBuffer sb = new StringBuffer() ;
            InputStream is = request.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String s = "" ;
            while((s=br.readLine())!=null){
                sb.append(s) ;
            }
            String result =sb.toString();
            log.info("\n\n ----------- 请求 json 为 :"+result);
        }catch (Exception e){
            ... 
        }

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Java调用API接口进行POST请求取出数据可以使用Java的网络请求库,比如Apache HttpClient或者OkHttp。下面是一个使用Apache HttpClient的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class APIClient { public static void main(String[] args) { CloseableHttpClient httpClient = HttpClients.createDefault(); try { // 创建POST请求 HttpPost httpPost = new HttpPost("API接口URL"); // 设置请求头 httpPost.addHeader("Content-Type", "application/json"); // 设置请求 String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}"; StringEntity requestEntity = new StringEntity(requestBody); httpPost.setEntity(requestEntity); // 发送请求获取响应 HttpResponse response = httpClient.execute(httpPost); // 处理响应 int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); System.out.println(responseBody); // 在这里处理响应数据 } else { System.out.println("请求失败:" + statusCode); } } catch (IOException e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 你需要将"API接口URL"替换为实际的API接口的URL,将请求的内容和请求头按照实际情况进行修改。在上述代码,我们使用了Apache HttpClient来发送POST请求,并使用EntityUtils工具类将响应转换为字符串。 请注意,这只是一个简单的示例,实际情况可能需要根据具的API接口进行参数的设置和数据的解析。同时,记得在使用完HttpClient后关闭连接以释放资源。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值