Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2.0, request GET to a .json file as endpoint

Hello Im working in a test with Retrofit 2.0 and one of the test is making a resquest to a url that finish with .json:

Example: https://domain.com/contacts.json

baseURl: https://domain.com/ endPoint: /contacts.json

Which is a file, but I want to make a normal GET request and get the json inside directly

like image 484
Ivor Avatar asked Apr 14 '16 21:04

Ivor


Video Answer


1 Answers

If you have control over your web server, you can customize it supports .json file as text/plain or application/json. Please see my following screenshot (I have done with IIS 7.5)

enter image description here

The following screenshot is a request using PostMan:

enter image description here

build.gradle file:

dependencies {
    ...    
    compile 'com.squareup.retrofit2:retrofit:2.0.1'
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
}

WebAPIService.java:

public interface WebAPIService {
    @GET("/files/jsonsample.json")
    Call<JsonObject> readJson();
}

MainAcitivty.java:

Retrofit retrofit1 = new Retrofit.Builder()
        .baseUrl("http://...")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

WebAPIService service1 = retrofit1.create(WebAPIService.class);
Call<JsonObject> jsonCall = service1.readJson();
jsonCall.enqueue(new Callback<JsonObject>() {
    @Override
    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
        Log.i(LOG_TAG, response.body().toString());
    }

    @Override
    public void onFailure(Call<JsonObject> call, Throwable t) {
        Log.e(LOG_TAG, t.toString());
    }
});

Logcat:

04-15 15:31:31.943 5810-5810/com.example.asyncretrofit I/AsyncRetrofit: {"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}
like image 56
BNK Avatar answered Sep 19 '22 01:09

BNK