如果您可以控制您的Web服务器,您可以自定义它支持将
.json
文件作为
text/plain
或
application/json
。请参见下面的截图(我已经在IIS 7.5上完成了)
![enter image description here](https://istack.dev59.com/sgSNB.webp)
以下截图是使用PostMan发送的请求:
![enter image description here](https://istack.dev59.com/uGM3l.webp)
build.gradle文件:
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());
}
});
日志记录:
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"}}}}}
https://domain.com/
,终端点设置为contacts.json
。 - EpicPandaForce