调用不同类中的改装。

huangapple 未分类评论51阅读模式
英文:

to call the retrofit in different classes

问题

我是 Android 初学者。我正在使用 Retrofit 来调用 API。但我想只编写一次 Retrofit 调用方法,并在我的应用程序中的不同 API 调用中使用相同的函数。我尝试在非活动类中创建一个通用方法,然后在我的活动类中使用它。

public static generic_Retrofit_Class apiClient;
private Retrofit retrofit = null;

public static generic_Retrofit_Class getInstance() {
    if (apiClient == null) {
        apiClient = new generic_Retrofit_Class();
    }
    return apiClient;
}

public Retrofit getclient() {
    return getclient(null);
}

private Retrofit getclient(Object o) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.level(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
    okHttpClient.readTimeout(60, TimeUnit.SECONDS);
    okHttpClient.writeTimeout(60, TimeUnit.SECONDS);
    okHttpClient.connectTimeout(60, TimeUnit.SECONDS);
    okHttpClient.addInterceptor(interceptor);
    okHttpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(Constant.Baseurl)
            .client(okHttpClient.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    return retrofit;
}

在这段代码之后,当我在我的活动类中调用这个方法时,它会显示一个错误。以下是在活动类中实现该方法的代码。

private void Getstock() {
    final String mid = medicineid.getText().toString().trim();
    final String batch = batchno.getText().toString().trim();

    if (medicineid.getText().length() != 0 && batchno.getText().length() != 0) {
        App_Interfaces app_interfaces = (App_Interfaces) new generic_Retrofit_Class().getclient().create(App_Interfaces.class);
        Map<String, String> mapdata = new HashMap<>();
        mapdata.put("mid", mid);
        mapdata.put("batch", batch);
        final Call<Response> getstock_call = app_interfaces.getstock(mapdata);

        getstock_call.enqueue(new Callback<Response>() {
            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {
                if (response.isSuccessful() && response.body() != null && response != null) {
                    String jsonresponse = response.body().toString();
                    parseStockData(jsonresponse);
                    System.out.print(jsonresponse);
                    return;
                }
            }

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

            }
        });
    }
}

这是错误信息:

java.lang.IllegalArgumentException: 'retrofit2.Response' is not a valid response body type. Did you mean ResponseBody?
for method App_Interfaces.getstock

以下是我的接口代码:

public interface get_stock {
    @GET("/getstock")
    Call<Response> getstock(@QueryMap Map<String, String> options);
}
英文:

I am a beginner to the android. I am using Retrofit to call the API. But I would like to write the retrofit call method only once and use the same function in different API calls in my application. I try to create It's a generic method in nonactivity class and use it in my activity class.

public static generic_Retrofit_Class apiClient;
private Retrofit retrofit = null;

public static generic_Retrofit_Class getInstance() {
    if (apiClient == null) {
        apiClient = new generic_Retrofit_Class();
    }
    return apiClient;
}


public Retrofit getclient()
{
    return getclient(null);
}

private Retrofit getclient(Object o) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.level(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
    okHttpClient.readTimeout(60, TimeUnit.SECONDS);
    okHttpClient.writeTimeout(60, TimeUnit.SECONDS);
    okHttpClient.connectTimeout(60, TimeUnit.SECONDS);
    okHttpClient.addInterceptor(interceptor);
    okHttpClient.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(Constant.Baseurl)
            .client(okHttpClient.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    return retrofit;
}

After this code when I call this method in my Activity class it shows an error. Here is the implementation of the method in the Activity class.

private void Getstock() {
    final String mid = medicineid.getText().toString().trim();
    final String batch = batchno.getText().toString().trim();

    if (medicineid.getText().length() != 0 &amp;&amp; batchno.getText().length() != 0) {
        App_Interfaces app_interfaces = (App_Interfaces) new generic_Retrofit_Class().getclient().create(App_Interfaces.class);
        Map&lt;String, String&gt; mapdata = new HashMap&lt;&gt;();
        mapdata.put(&quot;mid&quot;, mid);
        mapdata.put(&quot;batch&quot;, batch);
        final Call&lt;Response&gt; getstock_call = app_interfaces.getstock(mapdata);

        getstock_call.enqueue(new Callback&lt;Response&gt;() {
            @Override
            public void onResponse(Call&lt;Response&gt; call, Response&lt;Response&gt; response) {
                if (response.isSuccessful() &amp;&amp; response.body() != null &amp;&amp; response != null) {
                    String jsonresponse = response.body().toString();
                    parseStockData(jsonresponse);
                    System.out.print(jsonresponse);
                    return;
                }


            }

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

            }
        });
    }

Here is the error

> java.lang.IllegalArgumentException: 'retrofit2.Response' is not a valid response body type. Did you mean ResponseBody?
> for method App_Interfaces.getstock

here is my Interface Code

public interface get_stock 
   {
        @GET(&quot;/getstock&quot;)
        Call&lt;Response&gt; getstock(@QueryMap Map&lt;String, String&gt; options);
   }

答案1

得分: 0

欢迎来到SO

getClient方法的代码更改为

public class YOUR_CLASS{

   private static YOUR_API_INTERFACE retrofit = null;

   public static YOUR_API_INTERFACE getClient() { // 无需传递对象参数

     if(retrofit == null){

         //与您在问题中编写的客户端代码相同

         retrofit = new Retrofit.Builder()
                     .baseUrl(Constant.Baseurl)
                     .client(okHttpClient.build()) //来自您的客户端代码的okHttpClient
                     .addConverterFactory(GsonConverterFactory.create())
                     .build();

      }
      return retrofit.create(YOUR_API_INTERFACE.class);
   }
}

现在,您可以通过YOUR_CLASS.getClient()轻松访问Retrofit API接口。这将返回您的Retrofit接口

您的Retrofit接口声明方法应如下所示

public interface YOUR_API_INTERFACE {
   @GET("your api name")
   Call<YOUR_POJO> yourApi();
}

在您的activity/fragment类中,您可以访问yourApi方法,如下所示

YOUR_CLASS.getClient().yourApi();
英文:

Welcome to SO

Change the getClient method code as

public class YOUR_CLASS{

   private static YOUR_API_INTERFACE  retrofit = null;

   public static YOUR_API_INTERFACE getClient() { // no need to pass the object params
      
     if(retrofit == null){
     
         //you client code same as you written in question
     
         retrofit = new Retrofit.Builder()
                     .baseUrl(Constant.Baseurl)
                     .client(okHttpClient.build()) //okHtttpClient from your client code
                     .addConverterFactory(GsonConverterFactory.create())
                     .build();
          
      }
      return retrofit.create(YOUR_API_INTERFACE.class);
   }
}

Now, you can easily access the retrofit api interface by YOUR_CLASS.getClient(). This will return your Retrofit Interface

Your Retrofit Interface with declare method should be like this

public interface YOUR_API_INTERFACE {
   @GET(&quot;your api name&quot;)
   Call&lt;YOUR_POJO&gt; yourApi();
}

In your activity/fragment class you can access the yourApi method as

YOUR_CLASS.getClient().yourApi();

huangapple
  • 本文由 发表于 2020年4月9日 13:04:20
  • 转载请务必保留本文链接:https://java.coder-hub.com/61114314.html
匿名

发表评论

匿名网友

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

确定