Spring - java http get请求,返回字符串多加了一层引号“

博客讲述了在处理HTTP接口返回数据时遇到的问题,即GET请求返回的字符串被额外包裹了一层双引号。作者发现这是由于设置返回类型为`application/json`导致的,而原本期望的是纯文本。通过将`produces`属性改为`MediaType.TEXT_PLAIN`,成功解决了字符串显示异常的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    公司其他项目的同事调用我们模块的一个GET接口时,发现返回的字符串多了一层引号,刚看到这个问题,一脸疑惑,String类型的字符串不就是应该是这样的吗?

String result1= HttpUtil.get("http://localhost:8080/demo-service/v1/api/email/content?id=27");
System.out.println(result1);

输出:"https://demofile.aliyun.com/27.html"

    自己写了一个简单的HTTP Get请求一下,果然是这个样子的,但是我是直接从数据库拿到的这个url的啊,怎么跟平常的String不太一样?

    平常普通的字符串是这样的:

String result3 = "https://demofile.aliyun.com/27.html";
System.out.println(result3);

输出:https://demofile.aliyun.com/27.html

    神奇哦~~~

    猛然瞥见自己写的@RequestMapping,顿时觉得找到问题所在了!

    看来是把返回的数据类型配置成了application/json,怪不得加了一层双引号,改成文本类型就好了text/plain

修改前:
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation("获取邮件信息-对外api")
    @RequestMapping(value = "/email/content", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", value = "Authorization", required = true, dataType = "string", paramType = "header")})
    public String getEmailInfo(@RequestParam(value = "id") Integer id) {
        return emailService.getEmailUriFormOss(id);
    }

修改后:
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation("获取邮件信息-对外api")
    @RequestMapping(value = "/email/content", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN)
    @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", value = "Authorization", required = true, dataType = "string", paramType = "header")})
    public String getEmailInfo(@RequestParam(value = "id") Integer id) {
        return emailService.getEmailUriFormOss(id);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值