700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 【http 请求返回状态码 500 】 Spring Boot 模拟http请求

【http 请求返回状态码 500 】 Spring Boot 模拟http请求

时间:2020-12-03 20:29:11

相关推荐

【http 请求返回状态码 500 】  Spring  Boot 模拟http请求

背景

最近弄的项目中要求给另外一个服务器传送数据,预定是用http的方式,在开始动手之前我打算用Spring Boot模拟下服务器之间的请求

流程:服务器A发起POST请求将Json格式的数据发送到服务器B,服务器B要回传"success",当服务器A接收到"success"后表示数据发送成功

@Controllerpublic class MyController {/*** 服务器A*/@ResponseBody@RequestMapping(value = "/send", method = RequestMethod.GET)public String function8(){String sendMsg = (new User("1","12","123")).toString();String data = "this is null string";String url = "http://localhost:8080/receive";try {data = HttpHelper.ShareHelper().Post(url, sendMsg, "UTF-8", null,new HttpHelperRequestHandler() {@Overridepublic void OnPreSend(URLConnection request) {request.addRequestProperty("Content-type", "application/json");}});} catch (Exception e) {e.printStackTrace();}finally {if(!("success".equals(data))){System.out.println("服务器A:"+"发送通知失败");}else{System.out.println("服务器A:"+"发送通知成功");}}return "xixi";}/*** 服务器B*/@ResponseBody@RequestMapping("/receive")public String hello111(@RequestBody String user){System.out.println("服务器B:"+"接收成功,接收的到数据:");return "success";}}

点击运行之后,和预期显示的一样

偶然间,我发现如果服务器B不用注解@ResponseBody的话,服务器B仍然能接收到数据,但是服务器A这边会报500错误

(自己打印的)

@ResponseBody的作用是将返回的数据变成Json格式

也就是说在服务器A这边原本要用data接收Json格式的"success",但是服务器B却返回了一个 Object 过来,因此导致出现500错误码

解决:

如果不用注解@ResponseBody的话,就给服务器B这边的response设置ContentType为application/json,然后通过输出流来回写"success"

@Controllerpublic class MyController {/*** 服务器A*/@ResponseBody@RequestMapping(value = "/send", method = RequestMethod.GET)public String function8(){String sendMsg = (new User("1","12","123")).toString();String data = "this is null string";String url = "http://localhost:8080/receive";try {data = HttpHelper.ShareHelper().Post(url, sendMsg, "UTF-8", null,new HttpHelperRequestHandler() {@Overridepublic void OnPreSend(URLConnection request) {request.addRequestProperty("Content-type", "application/json");}});} catch (Exception e) {e.printStackTrace();}finally {if(!("success".equals(data))){System.out.println("服务器A:"+"发送通知失败"+data);}else{System.out.println("服务器A:"+"发送通知成功"+data);}}return "xixi";}/*** 服务器B*/@RequestMapping("/receive")public void hello11(@RequestBody String user,HttpServletResponse response){System.out.println("服务器B:"+"接收成功,接收的到数据:"+user);response.setContentType("application/json");try{PrintWriter write = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));write.print("success");write.flush();}catch(Exception e){}}}

运行之后

总结

出现500错误,一般是接收方那边程序报错,具体问题还要接收方那边反应,可能是没有正确处理好数据的接收或者数据的回写,其主要是对数据格式的检查。

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