开发者

java如何实现postman中用x-www-form-urlencoded参数的请求

开发者 https://www.devze.com 2024-09-29 10:27 出处:网络 作者: 黄黄黄黄黄莹
目录Java postman用x-www-form-urlencoded参数的请求java代码实现(以post方法为例)java实现postman为x-www-form-urlencoded的调用客户端实现服务端实现总结java postman用x-www-form-urlencoded参数的请求
目录
  • Java postman用x-www-form-urlencoded参数的请求
    • java代码实现(以post方法为例)
  • java实现postman为x-www-form-urlencoded的调用
    • 客户端实现
    • 服务端实现
  • 总结

    java postman用x-www-form-urlencoded参数的请求

    首先,先给出postman的参数构造:

    java如何实现postman中用x-www-form-urlencoded参数的请求

    java代码实现(以post方法为例)

    PostMethod postMethod = new PostMethod(valueConfig.getImpsAuthUrl()) ;
    postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
    //参数设置,需要注意的就是里边不能传NULL,要传空字符串
    //key  value 形式参数
    NameValuePair[] data = {
             new NameValuePair("username","test"),
             new NameValuePair("password","test123")
    };
    postMethod.setRequestBody(data);
    HttpClient httpClient = new HttpClient();
    int response = httpClient.executeMethod(postMethod); // 执行POST方法
    String result = postMethod.getResponseBodyAsString() ;  //返回结果
    
    if (response == 200 && result != null) {
    		//成功后的逻辑
    		DOSth();
            log.info("获取请求,result={}", result);
    }

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

    客户端实现

    导入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);
    
      js          String data = "json_json_json_json";
                StringRequestEnhttp://www.devze.comtity 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);
          python      System.out.println("响应" + result);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

    服务端实现

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

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

    0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    关注公众号