客户端接收Java服务端post请求返回的json出现405

决定了,以后每遇到一个问题就写篇博客记录一下,万一能帮到人呢。

客户端接收Java服务端post请求返回的json出现405

今天写一个图片上传的demo,服务端和客户端都是自己实现的,一开始在上传图片时用post请求很顺利的把图片上传到服务端了,后来想返回点数据,于是直接在服务端返回了个json,在客户端左边用gson转map,结果炸了……仔细检查创建json的语句,没毛病,再试一次把response的数据打印出来,结果:

<!doctype html><html lang="en"><head><title>HTTP Status 405 – Method Not Allowed</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 405 – Method Not Allowed</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> HTTP method POST is not supported by this URL</p><p><b>Description</b> The method received in the request-line is known by the origin server but not supported by the target resource.</p><hr class="line" /><h3>Apache Tomcat/9.0.10</h3></body></html>

什么鬼……
看上去是html,把它放浏览器里面解析(其实这段我是直接贴上面那段数据的,csdn的编辑器可以自动解析):

HTTP Status 405 – Method Not Allowed

HTTP Status 405 – Method Not Allowed


Type Status Report

Message HTTP method POST is not supported by this URL

Description The method received in the request-line is known by the origin server but not supported by the target resource.


Apache Tomcat/9.0.10

看上去就比较好理解了,服务端那边肯定哪里写错了。我网上搜了了些资料,看到有些说是“使用post方式请求js、html这样的静态文件一般的web服务器都会返回405 Method Not Allowed”,建议用get请求。然鹅,我并没有请求静态文件啊,而且上传图片只能用post啊……,
后来我摸索了一段时间,无果,再后来看了网上别人一些post请求的写法,发现很多人的Servlet都是用doGet调用doPost,或者发过来,所有业务都放在一个方法里面写,我是把get和post都分开写的,于是我就学着把doPost里面的东西搬到doGet方法里面,于是,居然可以返回正确的数据了……
但我分析了一下代码,觉得不应该是doGet的功劳,仔细对比两个方法,发现,我的doPost方法里面第一句有“super.doPost(req, response);”,我仿佛看见黑夜里的一缕星光,于是把代码改回去并把那句“super.doPost(req, response);”干掉,果然可以取到map,再把那句“super.doPost(req, response);”加上,果然又是405,这回真的证明是那句语句的锅……
前面说到很多人的Servlet都是用doGet调用doPost,或者发过来,所有业务都放在一个方法里面写,我猜这样写无论是get还是post都能访问,如果一开始决定用post,后面又改为get,这样的方式就不需要把代码在两个方法间搬来搬去了,而且有些通用的逻辑如返回json就不需要写两次了。
以上,仅是本小白的经验总结,若哪里有不对的地方,望大神们指出(如果有人看的话……)

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值