当我将 Retrofit2.0 与 POST 一起使用时,主体为 null ,但响应代码为 5xx?

When i use Retrofit2.0 with POST , body is null , but the reponse code is 5xx?

 Gson gson = new Gson();
    String json = gson.toJson(account);
    System.out.println(json);
    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
    p2PApi.createDepositAcct(body).enqueue(new Callback<Create>() {
        @Override
        public void onResponse(Call<Create> call, Response<Create> response) {
            try {

                System.out.println(response.code());
                System.out.println(response.errorBody().string());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<Create> call, Throwable t) {

        }
    });

这是我的代码,响应成功,但是response.code()=518,并且 响应消息在 response.errorBody() 中,reponse.body() 为空。

为什么要回复 518?

518 是什么意思?

正如您从 Retrofit API 文档中看到的那样

https://square.github.io/retrofit/2.x/retrofit/

public T body()

The deserialized response body of a successful response.

响应成功是什么意思?

public boolean isSuccessful()

Returns true if code() is in the range [200..300).

以及errorbody方法说明

public okhttp3.ResponseBody errorBody()

The raw response body of an unsuccessful response.

响应不成功表示代码不在范围(200-300)内,isSuccessful()函数中有描述。

如果您的代码是 518,消息肯定在 errorbody()

关于HTTP状态码的信息,一般可以参考这里 https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

5xx状态码是服务器错误,虽然我不知道518到底是什么错误,但通常应该是服务器端错误。

如 RFC7231,“6. 响应状态代码”所述。

The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request.

HTTP status codes are extensible. HTTP clients are not required to understand the meaning of all registered status codes, though such understanding is obviously desirable. However, a client MUST understand the class of any status code, as indicated by the first digit, and treat an unrecognized status code as being equivalent to the x00 status code of that class, with the exception that a recipient MUST NOT cache a response with an unrecognized status code.

For example, if an unrecognized status code of 471 is received by a client, the client can assume that there was something wrong with its request and treat the response as if it had received a 400 (Bad Request) status code. The response message will usually contain a representation that explains the status.

通常情况下,状态代码是为某些常用用途预定义的,并且可以扩展。这意味着可能有一些像 518 这样的状态代码,但如果您在网上搜索则没有确切的含义(因为它是自定义的 http 状态代码)。但是您可以将其视为服务器端错误之一(5xx 错误)