之前遇到一个问题,如果是get方法,
我可以很简单的构造强制链接结构
/function/{userId}
或是参数结构
/function?userId=123
@RequestMapping("/function")
@ResponseBody
public String function(@RequestParam("userId") String userId){
return "result";
}
然后就可以
get方法调试很简单,在网页中请求就完成了,如果是POST怎么办?
本文将介绍一个使用java代码发送POST请求的方式:
class A{
String a;
String b;
//省略getter,setter
...
}
@RequestMapping(value = "/functionPost", method = RequestMethod.POST)
@ResponseBody
public String functionPost(@RequestBody A a) {
return "result";
}
@ResponseBody
@Test
public void jsonPost() {
String strURL = "http://localhost:8080/newBsCard";
try {
URL url = new URL(strURL);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); // 设置发送数据的格式
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
A bean = new A();
bean.setA("23");
bean.setB("23");
String a = JSONObject.toJSONString(bean);
out.append(a);
out.flush();
out.close();
int code = connection.getResponseCode();
InputStream is = null;
if (code == 200) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
// 读取响应
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
String result = new String(data, "UTF-8"); // utf-8编码
System.out.println(result);
//return result;
}
} catch (IOException e) {
//LOG.error("Exception occur when send http post request!", e);
}
}
上面的代码,改自:
https://blog.csdn.net/java173842219/article/details/54020168
参考
https://blog.csdn.net/ff906317011/article/details/78552426
该文章简单介绍了@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别
参考
https://www.cnblogs.com/dflmg/p/6364141.html
该文章,使用ajax请求。不过里面说明了请求的时候,发送到服务端的内容被解析的方式。
https://www.cnblogs.com/qiankun-site/p/5774300.html
参考
https://blog.csdn.net/ljxbbss/article/details/74452326
该文章用实例说明了400错误的情况,以及用postman进行测试的方式
400错误:表示数据的参数类型错误
https://www.cnblogs.com/beppezhang/p/5824986.html
415错误:表示格式错误,比如content-type 参数搞错了。
https://blog.csdn.net/majinggogogo/article/details/78383772
500系统错误。https://blog.csdn.net/xiejunna/article/details/70049094
POSTMan的使用
https://blog.csdn.net/afterlife_qiye/article/details/62218572
参考
这个文章,对接受的参数类型聊得更深刻。
https://blog.csdn.net/m0_37499059/article/details/78798077
参考
使用mock测试的方式,没有实践过,记下
https://www.cnblogs.com/knyel/p/7901034.html
文章中给了三种传入方式
https://blog.csdn.net/lx_yoyo/article/details/72871091
springboot的测试方式
http://somefuture.iteye.com/blog/2247207