java如何实现postman中用x-www-form-urlencoded参数的请求
更新时间:2024年09月29日 09:05:39 作者:黄黄黄黄黄莹
在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";
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java使用Apache POI和EasyExcel读取Excel文件的实现方案
Java 读取 Excel 文件核心依赖 Apache POI(兼容 .xls(Excel 97-2003)和 .xlsx(Excel 2007+))或 EasyExcel(阿里开源,低内存、高性能),以下是两种主流方案的完整实现,需要的朋友可以参考下2025-12-12
Spring与MyBatis集成 AOP整合PageHelper插件的操作过程
Spring与MyBatis集成的主要目的是为了提供更强大的数据访问和事务管理能力,以及简化配置和提高开发效率,这篇文章主要介绍了Spring与MyBatis集成AOP整合PageHelper插件,需要的朋友可以参考下2023-08-08
Java基于装饰者模式实现的图片工具类实例【附demo源码下载】
这篇文章主要介绍了Java基于装饰者模式实现的图片工具类,结合完整实例形式分析了装饰者模式实现图片的判断、水印、缩放、复制等功能,并附带demo源码供读者下载参考,需要的朋友可以参考下2017-09-09


最新评论