100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > restclient发送json_如何使用restclient来发送post请求参数

restclient发送json_如何使用restclient来发送post请求参数

时间:2020-10-17 15:49:44

相关推荐

restclient发送json_如何使用restclient来发送post请求参数

Web程序:使用GET和POST方法发送请求 首先利用MyEclispe+Tomcat写好一个Web程序,实现的功能就是提交用户信息:用户名和年龄,使用GET和POST两种提交方式。 用浏览器打开: 不管以哪一种方式,提交以后显示如下页面,将提交的信息再显示出来。

我喜欢使用restclient 来测试我的 REST 风格的应用程序。一般我就是用GET方法,今天用到了POST方法。POST传递参数应该放在body里面,对长度没有限制。不像GET对URL的限制是1024字节。

运行restclient ,点选Method选项卡的“POST”方法。然后选择Body选项卡,下下拉列表中选择”String body“的选项,配置上 application/x-www-form-urlencoded;charset=UTF-8 。再出现的body里面写入字符串,也就是你的请求条件,如:query=xpsF

这样就可以传递post的参数了。

java代码如下:springmvc写的

@RequestMapping(value = "/test", method = { RequestMethod.GET,

RequestMethod.POST })

public void test(HttpServletResponse response, @RequestBody String message) {

//注意这里的:@RequestBody String message

LOGGER.debug(String.format("receive message %s", message));

Map map = Maps.newHashMap();

try {

map.put("result", message);

Tools.printToJson(JSON.toJSONString(map), response);

} catch (Exception e) {

LOGGER.error(e.getMessage(), e);

}

}

如果传递的是一个对象给springmvc,如(代码不全):

public class EntitySubscribe {

private Long entityId;

private String entityCode;

private String entityName;

private String teamCode;

private SubscribeUsesEnum subscribeUsesEnum;

private Date gmtCreate;

private Date gmtModify;

private Long flowId;

private OnOffEnum state;

private String reason;

private List uses;

}

mvc代码:

@ResponseBody

@RequestMapping(value = "/subscribeEntity", method = { RequestMethod.POST })

public AjaxResult subscribeEntity(@RequestBody EntitySubscribe entitySubscribe, @CookieValue(

value = Const.COOKIE_USER_KEY, required = false) String userId) {

LOGGER.debug(this.getClass().getName() + "#subscribeEntity");

long entityId = entitySubscribe.getEntityId();

String teamCode = entitySubscribe.getTeamCode();

String subscribeUses = Joiner.on(",").skipNulls().join(entitySubscribe.getUses());

String reason = entitySubscribe.getReason();

Preconditions.checkArgument(StringUtils.isNotBlank(teamCode));

Preconditions.checkArgument(StringUtils.isNotBlank(subscribeUses));

Preconditions.checkArgument(StringUtils.isNotBlank(reason));

Preconditions.checkArgument(StringUtils.isNotBlank(userId));

return entitySubscribeService.subscribeEntity(entityId, teamCode, subscribeUses, reason, userId);

}

服务器端代码 [java] package org.xiazdong.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSe

使用restclient的请求为 :POST

String body 为:application/json; charset=UTF-8

body内容为:{"entityId":343,"reason":"for test测试","teamCode":"cdc","uses":[1,2,3]}

这样后台就能收到对象了。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。