java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java postman用x-www-form-urlencoded参数的请求

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

作者:黄黄黄黄黄莹

在Java开发中,模拟Postman发送x-www-form-urlencoded类型的请求是一个常见需求,本文主要介绍了如何在Java中实现这一功能,首先,需要通过导入http-client包来创建HTTP客户端,接着,利用该客户端发送Post请求

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

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

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);

            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());
        }
    }

服务端实现

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文