本文介绍了无法在android中使用retrofit2发出@Post请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在 android 中使用改造,但是每当我尝试从互联网检索数据时,我的应用程序都没有返回任何内容我的响应没有成功,我目前不知道如何修复错误尝试使用 https://jsonplaceholder.typicode.com 从此 URL 发布和检索数据.我无法弄清楚是什么导致了这种情况.

主活动

 private void createpost() {Post post2=new Post(1,"这是标题","10");呼叫<发布>postCall= mWebService.createPost(post2);postCall.enqueue(new Callback() {@覆盖public void onResponse(Call call, Response response) {如果(响应.isSuccessful()){Log.d(TAG,"response.isSuccessful()");mLog.setText(String.valueOf(response.code()));showPost(response.body());}}@覆盖public void onFailure(Call<Post> call, Throwable t) {}});}

界面

公共接口 MyWebService {String BASE_URL="https://jsonplaceholder.typicode.com/";改造改造=新改造.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).建造();@POST("帖子")呼叫<发布>createPost(@Body Post post);}
解决方案

由于未知原因 https://jsonplaceholder.typicode.com 抛出套接字超时异常,同时您可以检查另一个具有类似功能的网站 https://reqres.in/ 这里是附在帖子中的示例代码

final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);最终 OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).建造();final String host = "https://reqres.in/";改造改造 = new Retrofit.Builder().baseUrl(HttpUrl.parse(host)).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).建造();ReqResApi api = retrofit.create(ReqResApi.class);api.createUser(new User("silentsudo", "dev")).enqueue(新回调(){@覆盖public void onResponse(Call call, Response response) {System.out.println("响应成功:" + response.body().toString());}@覆盖public void onFailure(Call call, Throwable throwable) {System.err.println("调用api时出错");throwable.printStackTrace();}});

API

 interface ReqResApi {@POST("api/用户")呼叫createUser(@Body 用户帖子);}

POJO

class User {私人字符串名称;私人字符串工作;公共用户(字符串名称,字符串作业){this.name = 名称;this.job = 工作;}@覆盖公共字符串 toString() {返回用户{"+"名称='" + 名称 + '\'' +", 工作='" + 工作 + '\'' +'}';}}

I am learning how to use retrofit in android but whenever I try to retrieve data from the internet my app doesn't return anything My response doesn't come successful and I don't know how to fix the error currently I am trying to post and retrieve data from this URL using https://jsonplaceholder.typicode.com. I am unable to figure out what is causing this.

 private void createpost() {

        Post post2=new Post(1,"This is Title","10");

        Call<Post> postCall= mWebService.createPost(post2);

        postCall.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {

                if (response.isSuccessful())
                {
                    Log.d(TAG,"response.isSuccessful()");
                    mLog.setText(String.valueOf(response.code()));
                    showPost(response.body());

                }
            }

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

            }
        });


    }
public interface MyWebService {

 String BASE_URL="https://jsonplaceholder.typicode.com/";

Retrofit retrofit=new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    @POST("posts")
    Call<Post> createPost(@Body Post post);

}
解决方案

For unknown reason https://jsonplaceholder.typicode.com is throwing socket timeout exception, in the mean time you can check another website with similar functionality https://reqres.in/ here is the sample code attached to post

final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();
        final String host = "https://reqres.in/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpUrl.parse(host))
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ReqResApi api = retrofit.create(ReqResApi.class);

        api.createUser(new User("silentsudo", "dev"))
                .enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        System.out.println("Resp Success full: " + response.body().toString());
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable throwable) {
                        System.err.println("Error calling api");
                        throwable.printStackTrace();
                    }
                });

Api

 interface ReqResApi {
        @POST("api/user")
        Call<User> createUser(@Body User post);
    }

POJO

class User {
        private String name;
        private String job;

        public User(String name, String job) {
            this.name = name;
            this.job = job;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", job='" + job + '\'' +
                    '}';
        }
    }

这篇关于无法在android中使用retrofit2发出@Post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:53