Retrofit 2.0无法使用发布请求登录

时间:2018-06-29 13:19:24

标签: android post kotlin retrofit2

我正在尝试使用Retrofit 2.0登录网站。这是我第一次使用Retrofit。 但是,通过邮递员和网站,我可以成功登录。这是Chrome中的请求:enter image description here

那是我的代码:

APIService:

interface APIService {

    @FormUrlEncoded
    @POST("/account/")
    fun login(@Field ("login-ident") username:String,
              @Field ("login-pwd") password:String): Call<String>

}

MainActivty:

    fun login(username:String, password:String) {
    mAPIService?.login(username, password)?.enqueue(object : Callback<String> {
        override fun onResponse(call: Call<String>, response: Response<String>) {
            if (response.isSuccessful()) {
                showResponse(response.body().toString())
                Log.e("Tag", "post submitted to API.")
            }
        }

        override fun onFailure(call: Call<String>, t: Throwable) {
            Log.e("Tag", "Unable to submit post to API. - "+t.message)
        }
    })
}

fun showResponse(response: String) {
    Log.e("Tag", response)
}

基本上,当我运行请求时,我在响应正文中得到的是登录页面,而使用chrome或postman时,则检索用户页面(这就是我想要的)。我做错了什么?谢谢:D

更新:

这是邮递员生成的代码(并且可以,但是我的改装请求不起作用):

    POST /account/ HTTP/1.1
Host: www.placeoldersite.it
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: postman token

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="login-ident"

myusername
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="login-pwd"

mypassword
------WebKitFormBoundary7MA4YWxkTrZu0gW--

更新2:

我制作了一个小的python脚本,它可以工作,但是我的改装请求不起作用D:

    import requests
url = "https://www.myplaceholder.it/account/"
data = {"login-ident":"username", "login-pwd":"password"}

r = requests.post(url, data=data)

print(r.content)

更新3:

我认为问题在于我的代码Retrofit无法处理cookie(在这种情况下为一个cookie),并且我无法执行登录

3 个答案:

答案 0 :(得分:0)

Retrofit会自行在路径中添加“ /”。 尝试使用@POST(“ account”)

答案 1 :(得分:0)

请从@POST(“ / account /”)

@FormUrlEncoded
    @POST("/account")
    fun login(@Field ("login-ident") username:String,
              @Field ("login-pwd") password:String): Call<String>

我希望它对您有用。 :)

答案 2 :(得分:0)

我建议将代码包装在一个对象中,该对象也更易于处理,然后使用GSONMoshi之类的转换器适配器来转换响应,例如:

data class LoginModel(@SerializedName("login-ident") val userName: String,
                      @SerializedName("login-pwd") val password: String)

,并将其作为@Body参数和您的服务传递给登录功能。如果将LoginModel封装在json的data对象中,则可以创建包装器类,否则声明可以是:

interface LoginService {
    @POST("account")
    fun login(@Body loginModel: LoginModel): Call<String>
}

,然后与改造调用一起使用会更好。另外,请确保如果它是JSONObject,则从服务器获取字符串作为响应,我再次建议使用包装器data class LoginResponseModel,并将json结构定义为可由{{ 1}}或GSON。希望这会有所帮助:)