无法在安卓中使用Retrofit2进行@Post请求

huangapple go评论69阅读模式
英文:

Not able to make @Post request using retrofit2 in android

问题

我正在学习如何在 Android 中使用 Retrofit但每当我尝试从互联网检索数据时我的应用程序没有返回任何内容我的响应没有成功返回我不知道如何修复这个错误目前我正在尝试使用 https://jsonplaceholder.typicode.com 这个 URL 发布和检索数据。我无法弄清楚是什么原因引起了这个问题。

> MainActivity

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) {

        }
    });
}

> Interface

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);
}
英文:

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.

> MainActivity

 private void createpost() {

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

        Call&lt;Post&gt; postCall= mWebService.createPost(post2);

        postCall.enqueue(new Callback&lt;Post&gt;() {
            @Override
            public void onResponse(Call&lt;Post&gt; call, Response&lt;Post&gt; response) {

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

                }
            }

            @Override
            public void onFailure(Call&lt;Post&gt; call, Throwable t) {

            }
        });


    }

> Interface

public interface MyWebService {

 String BASE_URL=&quot;https://jsonplaceholder.typicode.com/&quot;;

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


    @POST(&quot;posts&quot;)
    Call&lt;Post&gt; createPost(@Body Post post);

}

答案1

得分: 3

以下是翻译好的部分:

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

```java
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("响应成功: " + response.body().toString());
            }

            @Override
            public void onFailure(Call<User> call, Throwable throwable) {
                System.err.println("调用 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 + '\'' +
                '}';
    }
}

<details>
<summary>英文:</summary>

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 

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

        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(&quot;silentsudo&quot;, &quot;dev&quot;))
                .enqueue(new Callback&lt;User&gt;() {
                    @Override
                    public void onResponse(Call&lt;User&gt; call, Response&lt;User&gt; response) {
                        System.out.println(&quot;Resp Success full: &quot; + response.body().toString());
                    }

                    @Override
                    public void onFailure(Call&lt;User&gt; call, Throwable throwable) {
                        System.err.println(&quot;Error calling api&quot;);
                        throwable.printStackTrace();
                    }
                });

Api

 interface ReqResApi {
        @POST(&quot;api/user&quot;)
        Call&lt;User&gt; 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 &quot;User{&quot; +
                    &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +
                    &quot;, job=&#39;&quot; + job + &#39;\&#39;&#39; +
                    &#39;}&#39;;
        }
    }

huangapple
  • 本文由 发表于 2020年5月29日 05:15:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/62074649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定