简体   繁体   中英

request post with retrofit in android

I want use request post in my app. I used this but I have a problem. I face this problem when I want to create an account.

status code 403

You can see my code:

Api.kt

interface Api {
@Headers("Content-Type: application/x-www-form-urlencoded")
@POST("users/signup")
@FormUrlEncoded
fun createUser(
    @Field("first_name") fName: String,
    @Field("last_name") lName: String,
    @Field("email") email: String,
    @Field("username") username: String,
    @Field("password") password: String,
) : Call<UserResponse>
}

UserResponse.kt

data class UserResponse(
val email: String,
val first_name: String,
val password: String,
val last_name: String,
val username: String
)

SignUpActivity.kt

binding.btnSignUp
        .setOnClickListener {

            val username = binding.etUsername.text.toString().trim()
            val password = binding.etPw.text.toString().trim()
            val fName = binding.etFName.text.toString().trim()
            val lName = binding.etLName.text.toString().trim()
            val email = binding.etEmail.text.toString().trim()

            if (username.isEmpty()) {
                binding.etUsername.error = "Password required"
                binding.etUsername.requestFocus()
                return@setOnClickListener
            }

            if (password.isEmpty()) {
                binding.etPw.error = "Password required"
                binding.etPw.requestFocus()
                return@setOnClickListener
            }

            val logging = HttpLoggingInterceptor()
            logging.level = HttpLoggingInterceptor.Level.BODY

            val httpClient = OkHttpClient.Builder()

            httpClient.addInterceptor(logging)
            val instance: Api by lazy {

                val retrofit: Retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build()
                retrofit.create(Api::class.java)
            }
            instance.createUser(fName, lName, email, username, password)
                .enqueue(object : Callback<UserResponse> {
                    override fun onFailure(call: Call<UserResponse>, t: Throwable) {
                        Toast.makeText(applicationContext, t.message, Toast.LENGTH_LONG).show()
                    }

                    override fun onResponse(
                        call: Call<UserResponse>,
                        response: Response<UserResponse>
                    ) {
                        Toast.makeText(applicationContext, response.code(), Toast.LENGTH_LONG)
                            .show()
                    }
                })

        }

I use this request on postman and it works good

enter image description here

but in android studio it didn't work and I have this error enter image description here

I hope u can help me

Here are the some modification, you can make :

step: 1 Add this permission in your AndroidMenifest.xml file

<uses-permission android:name="android.permission.INTERNET"/>

step: 2

UserResponse.java

public class UserResponse {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("first_name")
    @Expose
    private String firstName;
    @SerializedName("last_name")
    @Expose
    private String lastName;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("username")
    @Expose
    private String username;
    @SerializedName("groups")
    @Expose
    private List<Object> groups = null;
    @SerializedName("permissions")
    @Expose
    private List<Object> permissions = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<Object> getGroups() {
        return groups;
    }

    public void setGroups(List<Object> groups) {
        this.groups = groups;
    }

    public List<Object> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Object> permissions) {
        this.permissions = permissions;
    }

}

Step: 3 -> Add this methods to your activity and call method apiCall() in your onCreate() or appropriate place.

private fun getClient(): Retrofit? {
        val interceptor = HttpLoggingInterceptor()
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        val client: OkHttpClient = OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .retryOnConnectionFailure(true)
            .build()
        return Retrofit.Builder()
            .baseUrl("http://194.62.43.26:1337/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
    }

    private fun apiCall() {

        val firstname = "123"
        val lastname = "234"
        val email = "345@6.com"
        val username = "132456"
        val pw = "12345678"

        val call = getClient()!!.create(Api::class.java).createUser(
            firstname,
            lastname,
            email,
            username,
            pw
        )

        call.enqueue(object : Callback<UserResponse> {
            override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
                Toast.makeText(this@MainActivity, response.code().toString()
                        + " " + response.body().toString(), Toast.LENGTH_SHORT).show()
            }

            override fun onFailure(call: Call<UserResponse>, t: Throwable) {
                Toast.makeText(this@MainActivity, t.localizedMessage!!.toString(),
                    Toast.LENGTH_SHORT).show()
            }
        })
    }

Step: 4 Response is in the screen shot屏幕截图 - 响应

Happy Coding :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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