简体   繁体   English

改装后给出零响应

[英]Retrofit Post Gives Null Response

I went through some Stack questions on this but couldn't find an answer. 我对此进行了一些堆栈问题,但找不到答案。

Following is my request and response in PostMan 以下是我在PostMan中的要求和回复

在此处输入图片说明

Following is my Retrofit code. 以下是我的改造代码。 I have a LoginModel POJO class with username and token as fields and their respective getters and setters: 我有一个LoginModel POJO类,将用户名和令牌作为字段以及它们各自的获取器和设置器:

object ApiClient {

    val BASE_URL = "http://MyIpaddress:3005/api/"
    private var retrofit: Retrofit? = null

    val client: Retrofit
        get() {
            if (retrofit == null) {
                retrofit = Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
            }
            return retrofit!!
        }
}

public interface LoginApiInterface {



    @Headers("Content-Type: application/json")
    @POST("v1/account/login")
    Call<LoginModel> saveLoginModel(@Body String body);
}

Following is the code which gets called when user clicks LoginButton 以下是用户单击LoginButton时调用的代码

fun attemptLogin(){
        val email = et_email_activity_login.getText().toString()
        val password = et_password_activity_login.getText().toString()
        val apiInterface = ApiClient.client.create(LoginApiInterface::class.java)


        val jsonBody = JSONObject()
        jsonBody.put("email", email)
        jsonBody.put("password", password)
        val mRequestBody = jsonBody.toString()


        apiInterface.saveLoginModel(mRequestBody).enqueue(object: Callback<LoginModel>{
            override fun onFailure(call: Call<LoginModel>?, t: Throwable?) {
                Log.i("TAG",t!!.localizedMessage)
            }

            override fun onResponse(call: Call<LoginModel>?, response: Response<LoginModel>?) {

                Log.i("TAG","Post submitted"+response!!.body().toString())

            }

        } )

I am getting null in response!!.body().toString() . 我在response!!.body().toString()得到null response!!.body().toString()response!!.body().toString() When I did 当我做的时候

if (response!!.code() == 400) {
                    Log.v("Error code 400",response!!.errorBody()!!.string());
                }

I got this response: 我得到了这个回应:

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Error</title>
    </head>
    <body>
    <pre>SyntaxError: Unexpected token # in JSON at position 0<br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)<br> &nbsp; &nbsp;at createStrictSyntaxError (/home/pritish/Music/foodtruck-api/foodtruck-api/node_modules/body-parser/lib/types/json.js:157:10)<br> &nbsp; &nbsp;at parse (/home/pritish/Music/foodtruck-api/foodtruck-api/node_modules/body-parser/lib/types/json.js:83:15)<br> &nbsp; &nbsp;at /home/pritish/Music/foodtruck-api/foodtruck-api/node_modules/body-parser/lib/read.js:121:18<br> &nbsp; &nbsp;at invokeCallback (/home/pritish/Music/foodtruck-api/foodtruck-api/node_modules/raw-body/index.js:224:16)<br> &nbsp; &nbsp;at done (/home/pritish/Music/foodtruck-api/foodtruck-api/node_modules/raw-body/index.js:213:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (/home/pritish/Music/foodtruck-api/foodtruck-api/node_modules/raw-body/index.js:273:7)<br> &nbsp; &nbsp;at emitNone (events.js:115:13)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:218:7)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:1054:12)<br> &nbsp; &nbsp;at _combinedTickCallback (internal/process/next_tick.js:138:11)<br> &nbsp; &nbsp;at process._tickDomainCallback (internal/process/next_tick.js:218:9)</pre>
    </body>
    </html>

Are you sure the request is successful? 您确定请求成功吗?

Add a http login interceptor to see what you send and receive when making the actual request. 添加http登录拦截器以查看发出实际请求时发送和接收的内容。 ( https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor ) https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor

Also keep in mind that Retrofits onResponse is called for 4xx http response codes and your body() is null then. 还要记住,对4xx http响应代码调用了Retrofits onResponse,然后body()为null。 For those cases you should use the errorBody. 对于这些情况,应使用errorBody。 (onFailure is called for 500 error codes and other issues such as timeouts etc... (onFailure被要求提供500个错误代码和其他问题,例如超时等。

So do a following check as well in onRespose. 因此在onRespose中也进行以下检查。

if (response.isSuccessful()) { // checks if res code is in [200..300)
   // Parse the response.body()
} else {
   // Parse the response.errorBody()
}

The problem was in my server side code. 问题出在我的服务器端代码中。 I should have passed a JSON response after posting data. 发布数据后,我应该已经传递了JSON响应。

Also this link helped a lot: 这个链接也有很大帮助:

https://stackoverflow.com/questions/40817362/sending-json-in-post-request-with-retrofit2/40817747#40817747

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

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