简体   繁体   English

使用HTTP状态代码反映Web服务请求的成功/失败?

[英]Using HTTP status codes to reflect success/failure of Web service request?

I'm implementing a Web service that returns a JSON-encoded payload. 我正在实现一个返回JSON编码的有效负载的Web服务。 If the service call fails -- say, due to invalid parameters -- a JSON-encoded error is returned. 如果服务调用失败 - 例如,由于参数无效 - 将返回JSON编码的错误。 I'm unsure, however, what HTTP status code should be returned in that situation. 但是,我不确定在那种情况下应该返回什么HTTP状态代码。

On one hand, it seems like HTTP status codes are for HTTP: even though an application error is being returned, the HTTP transfer itself was successful, suggesting a 200 OK response. 一方面,似乎HTTP状态代码适用于HTTP:即使正在返回应用程序错误,HTTP传输本身也是成功的,建议200 OK响应。

On the other hand, a RESTful approach would seem to suggest that if the caller is attempting to post to a resource, and the JSON parameters of the request are invalid somehow, that a 400 Bad Request is appropriate. 另一方面,RESTful方法似乎暗示如果调用者试图发布到资源,并且请求的JSON参数以某种方式无效,那么400 Bad Request是合适的。

I'm using Prototype on the client side, which has a nice mechanism for automatically dispatching to different callbacks based on HTTP status code ( onSuccess and onFailure ), so I'm tempted to use status codes to indicate service success or failure, but I'd be interested to hear if anyone has opinions or experience with common practice in this matter. 我在客户端使用Prototype,它有一个很好的机制,可以根据HTTP状态代码( onSuccessonFailure )自动调度到不同的回调,所以我很想用状态代码来表示服务成功或失败,但我有兴趣听听是否有人对此事有共同惯例的意见或经验。

Thanks! 谢谢!

http status code are just for indicating the status of the application response. http状态代码仅用于指示应用程序响应的状态。 and as you said, if json parameters as somehow invalid, a 400 status code is an appropriate answer. 正如你所说,如果json参数以某种方式无效,400状态代码一个合适的答案。

so yes, it is a really good idea to use http status code. 所以是的,使用http状态代码是一个非常好的主意。 de plus, status code are then easy to understand as they don't change from an application (web services) to another de plus,状态代码易于理解,因为它们不会从应用程序(Web服务)更改为另一个应用程序

You should definitely use the proper status codes since they are exactly for this purpose, not to indicate the status of the HTTP request itself. 您绝对应该使用正确的状态代码,因为它们完全是出于此目的,而不是指示HTTP请求本身的状态。 By this way you can redirect the response to the appropriate function/branch before parsing it which will lead to a much tidier code in the client side. 通过这种方式,您可以在解析之前将响应重定向到相应的函数/分支,这将导致客户端中的代码更加整洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM