所以我想使用restTemplate.getForObject从一个url加载一个简单的JSON文件。我创建了一个只有一个字符串的简单 json 文件,但 android 无法加载它。但是,当我在模拟器的浏览器中输入 url 时,浏览器会显示我的 json 文件
知道为什么它不能与 restTemplate.getForObject 一起使用吗?
我的代码:
服务器调用者:
private static final String ipAddress = "192.168.56.1:8080";
private RestTemplate restTemplate = new RestTemplate();
private String test;
private List<HttpMessageConverter<?>> messageConverters;
private static ServerCaller instance = null;
private ServerCaller(){
messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
}
private static void createMessageService(){
if(instance == null){
instance = new ServerCaller();
}
}
public static ServerCaller getInstance(){
if(instance == null){
createMessageService();
}
return instance;
}
public ServerError getTest() {
try {
test = restTemplate.getForObject("http://" + ipAddress + "/ProjectTeamF-1.0/service/getTest.json", String.class);
} catch (ResourceAccessException rae) {
return ServerError.ServerNotFound;
} catch (HttpServerErrorException hsee) {
return ServerError.WrongData;
} catch (Exception e) {
return ServerError.OtherError;
}
return ServerError.NoError;
}
public String pakTest(){
return test;
}
然后在我看来:
serverCaller.getTest();
ServerError se = serverCaller.getTest();
Toast.makeText(getApplicationContext(),serverCaller.pakTest(),Toast.LENGTH_SHORT).show();