java时犯了什么错误?

hmmo2u0o  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(443)

我正试着用2来做一个http post,
我有技术规格

我在技术规格中有一个错误是可以接受的

我在下面发了一篇http帖子。但我总是

Response{protocol=http/1.1, code=422, message=Unprocessable Entity, url=https://XXX/api/v1/token/}.

有人能帮我吗?
api接口:

public interface PostService {
   @Headers({
           "Content-type: application/json"
   })
   @POST("api/v1/token/")
   Call<String> sendPosts(@Body Posts posts);

}
我的请求类(pojo):

public class Posts {

    @SerializedName("username")
    private String username;
    @SerializedName("password")
    private String password;
    @SerializedName("grant_type")
    private String grant_type;
    @SerializedName("scope")
    private String scope;
    @SerializedName("client_id")
    private String client_id;
    @SerializedName("client_secret")
    private String client_secret;

    public Posts() {
        username = "test";
        password = "test";

    }
}

我的活动中的改装后请求:

OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://xxxxxx/")
                    .client(okHttpClientBuilder.build())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            postsService = retrofit.create(PostService.class);  //l'oggetto retrofit deve rispettare ciò che è scritto nell'interfaccia creata PostService

            Posts post = new Posts();

            Call<String> call = postsService.sendPosts(post);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    System.out.println("TEST!!!!!!!!!!!!" +  response.toString());  //Response here 
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_LONG).show();
                }
            });
bn31dyow

bn31dyow1#

我解决了这个问题。正如@fabio piunti所说,我必须发送一个x-www-form-urlencoded,
所以我修改了代码如下:

public interface PostService {
    @Headers({
            "Content-Type: application/x-www-form-urlencoded"
    })

    @FormUrlEncoded  //I have added this as well
    @POST("api/v1/token/")
    Call<Posts> sendPosts( @Field("username") String title, @Field("password") String password);
}

我现在在活动中的要求是:

....

  Call<Posts> call = postsService.sendPosts("test", "test");
    //eseguo la mia chiamata (Call) post
    call.enqueue(new Callback<Posts>() {
        @Override
        public void onResponse(Call<Posts> call, Response<Posts> response) {

            System.out.println("TEST!!!!!!!!!!!!" +  response.toString());
        }

        @Override
        public void onFailure(Call<Posts> call, Throwable t) {
            System.out.println("TEST Error!!!!!!!!!!!!" + t.toString());

        }

    });

相关问题