@ResponseBody不明原因返回content-type为text/html,强制返回application/json

最近项目中遇到一个不明原因的事件,springMVC中使用@ResponseBody返回数据,报错404。
使用调试工具查看发现response的content-type期望为application/json,但实际上是text/html,因此使用json的解析方法会报错,目前想到了两种方法解决:
1. 接收数据后使用JSON.parse(),将接收到的数据进行json转换;
2. 后台声明时添加参数produces = {“application/json”},强制该返回为json格式数据。

@RequestMapping(value = "/loginSSO", produces = {"application/json"}, method = RequestMethod.POST)

目前问题暂时得到解决,至于为什么单独有个post方法,使用了@ResponseBody却返回html类型的数据,还需进一步查看。。。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
在Java中指定`content-type`为`application/x-www-form-urlencoded`有多种方式,以下是其中两种常见的方法: 1. 使用`HttpURLConnection`发送POST请求时,可以通过设置`setRequestProperty`方法来指定`content-type`为`application/x-www-form-urlencoded`,示例代码如下: ``` URL url = new URL("your_url"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 组装请求参数 String params = "param1=value1&param2=value2"; // 向服务器写入参数 OutputStream outputStream = conn.getOutputStream(); outputStream.write(params.getBytes()); outputStream.flush(); // 获取响应结果 int responseCode = conn.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String responseBody = response.toString(); ``` 2. 使用第三方库`OkHttp`发送POST请求时,可以通过设置`MediaType`为`MediaType.parse("application/x-www-form-urlencoded")`来指定`content-type`,示例代码如下: ``` OkHttpClient client = new OkHttpClient(); String url = "your_url"; String params = "param1=value1&param2=value2"; RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), params); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = client.newCall(request).execute(); String responseBody = response.body().string(); ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值