How do you get JSON Get request with Retrofit2?



  • What kind of responseObject is supposed to have so that you can get any answer and then you can't take it off?

    I'm building an interface:

    interface GitHubService {
        @GET("products")
        Call<ResObject> repoContributors();
    
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://somepath.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    

    }

    Implementing the request:

    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
    final Call<ResponseObject> call =
    gitHubService.repoContributors();

        call.enqueue(new Callback&lt;ResponseObject&gt;() {
            @Override
            public void onResponse(Call&lt;ResponseObject&gt; call, Response&lt;ResponseObject&gt; response) {
                final TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(response.body().toString());
            }
            @Override
            public void onFailure(Call&lt;ResponseObject&gt; call, Throwable t) {
                final TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText("Something went wrong: " + t.getMessage());
            }
        });
    }
    

    });



  • Try to ask a guy. JsonElement https://stackoverflow.com/a/25477954/3212712 :

    call.enqueue(new Callback<JsonElement>() {...});
    

    Further onResponse:

    JsonObject jsonObj = response.body().getAsJsonObject();
    String strObj = response.body().toString();
    

    Another option is to add the Interceptor, some of you get an untranspared answer.

    public static class MyInterceptor implements Interceptor {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request = chain.request();
    
        Response response = chain.proceed(request);
    
        Log.d(TAG, "response.body().string(): " + response.body().string());
    
        return response;
    }
    

    }

    It should be added to OkHtpClient, which should be added to Retrofit:

    OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new MyInterceptor())
    .build();

    Retrofit retrofit = new Retrofit.Builder()
    .client(client)
    //остальное
    .build();




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2