java实现postman为x-www-form-urlencoded的调用

文章展示了如何在Java中使用ApacheCommonsHttpClient库发送POST请求。客户端代码导入了http-client依赖,创建POST方法,设置请求体,并执行HTTP请求获取响应。服务端则通过@RequestMapping接收POST请求,处理@RequestBody中的JSON数据,并返回ok。
摘要由CSDN通过智能技术生成

1.客户端实现

导入http-client jar。

        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
public static void clientDemo() {
        try {
            String requestUrl = "http://hello/demo";
            PostMethod postMethod = new PostMethod(requestUrl);

            String data = "json_json_json_json";
            StringRequestEntity stringRequestEntity = new StringRequestEntity(data, "application/x-www-form-urlencoded", "utf-8");
            postMethod.setRequestEntity(stringRequestEntity);

            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();

            //调用接口
            int code = httpClient.executeMethod(postMethod);
            String result = postMethod.getResponseBodyAsString();

            System.out.println("接口状态" + code);
            System.out.println("响应" + result);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

2.服务端实现

@RequestMapping(value = "/receive", method = RequestMethod.POST)
    @ResponseBody
    public String receiveFare(@RequestBody String str) {
        System.out.println("接到数据:" + str);
        return "ok";
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值