2015-12-11 161 views
0

当我尝试使用微信公共平台时,微信服务器将调用我的一个API,我需要返回一个令牌来验证我的身份。但是,当我直接返回令牌时,weChat服务器会提示验证错误。@ResponseBody和HttpServletResponce之间有什么区别

@RequestMapping(value="/userFollow", method= RequestMethod.GET) 
@ResponseBody 
public String weChatToken(HttpServletRequest request,String signature,String timestamp,String nonce,String echostr,HttpServletResponse response) throws IOException, DocumentException { 
    String result=weChatService.checkSignature(signature,timestamp,nonce,echostr); 
    return result; 
} 

然后我改变了我的代码如下。这一次,验证是正确的。

@RequestMapping(value="/userFollow", method= RequestMethod.GET) 
    @ResponseBody 
    public String weChatToken(HttpServletRequest request,String signature,String timestamp,String nonce,String echostr,HttpServletResponse response) throws IOException, DocumentException { 
     String result=weChatService.checkSignature(signature,timestamp,nonce,echostr); 
     PrintWriter pw=response.getWriter(); 
     pw.write(result); 
     pw.flush(); 
     return null; 
    } 

我用Google搜索,并得到了使用@Responsebody时,春消息写入响应的主体。 那么他们之间有什么区别?为什么第一种方法是错误的?

+0

responseBody只是响应的主体,而'HttpServletResponce'包含整个响应,例如标题,Cookie,正文等。 –

+0

发布的代码是否正确?两种方法都有@ResponseBody? –

回答

1

HTTP响应由一个状态码,一些标题和一个正文组成。使用@ResponseBody意味着你的方法给出了正文的内容,没有别的。使用HttpServletResponse使您的方法可以设置响应的所有方面,但是使用起来有点不方便。

0

你应该使用ResponseBody来返回一些数据结构。由于您只需要“唯一”字符串,因此您应该将方法的返回类型更改为从String中除去并移除ResponseBody注释。

@RequestMapping(value="/userFollow", method= RequestMethod.GET) 
public void weChatToken(HttpServletRequest request,String signature,String timestamp,String nonce,String echostr,HttpServletResponse response) throws IOException, DocumentException { 
    String result=weChatService.checkSignature(signature,timestamp,nonce,echostr); 
    PrintWriter pw=response.getWriter(); 
    pw.write(result); 
    pw.flush(); 
} 
相关问题