Reputation: 578
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
Upvotes: 7
Views: 10957
Reputation: 578
Hello I found a solution to get the file using your code and it really works now but I haven't touch the MIME on the web server, I think I didn't have added the Converter in the code I guess. Thank you.
WebAPIService.java:
public interface WebAPIService {
@GET("/contacts.json")
Call<JsonObject> getContacts();
}
MainAcitivty.java:
Retrofit retrofit1 = new Retrofit.Builder()
.baseUrl(BuildConfig.API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
WebAPIService service1 = retrofit1.create(WebAPIService.class);
Call<List<Contact>> jsonCall = service1.getContacts();
jsonCall.enqueue(new Callback<List<Contact>() {
@Override
public void onResponse(Call<List<Contact>> call, Response<List<Contact>> response) {
Log.i(LOG_TAG, response.body().toString());
}
@Override
public void onFailure(Call<List<Contact>> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Upvotes: 6
Reputation: 24114
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)
The following screenshot is a request using PostMan:
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"}}}}}
Upvotes: 8