Answer the question
In order to leave comments, you need to log in
How to get an object in a restful application?
Hello. Help, please, to solve a problem. I am writing a resful application. I return a list of objects from the main application
List<User> users = new ArrayList<>();
Tariff tariff = tariffService.getTariffByTitle(contractTitle);
for (Contract contract : contractService.getAll()) {
if (contract.getTariff().equals(tariff)) {
contract.getUser().setPassword("");
users.add(contract.getUser());
}
}
return users;
String output = null;
String URLstring = "http://localhost:8080/getRestInfo?contract=base";
URL url = new URL(URLstring);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Basic " +
new String(new Base64().encodeBase64("[email protected]:12345".getBytes())));
if (conn.getResponseCode() != 200) {
System.out.println("Failed : HTTP error code : "
+ conn.getResponseCode());
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
output = br.readLine();
conn.disconnect();
List<User> users = (List<User>) br;
System.out.println(output);
Answer the question
In order to leave comments, you need to log in
Try to do it on a spring RestTemplate as described here . An example of how to get List<User> users
here
PS
String output = null;
String URLstring = "http://localhost:8080/getRestInfo?contract=base";
URL url = new URL(URLstring);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Basic " +
new String(new Base64().encodeBase64("[email protected]:12345".getBytes())));
if (conn.getResponseCode() != 200) {
System.out.println("Failed : HTTP error code : "
+ conn.getResponseCode());
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
output = br.readLine();
/**
* Здесь в output переменной у Вас в output лежит json, чтобы преобразовать его в java бины нужен парсер (это называется десериализовать), наиболее популярные - Gson или Jackson
*/
Gson gson = new Gson();
Type userListType = new TypeToken<ArrayList<User>>() {}.getType();
List<User> users = gson.fromJson(output, userListType);
conn.disconnect();
System.out.println(output);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question