Код: Выделить всё
Class ApiService
public class ApiService {
AddressDto addressDto = new AddressDto();
// Esse método vai retornar uma classe DTO de endereco
public AddressDto getEndereco(String cep) throws IOException, InterruptedException {
try {
HttpClient client = HttpClient.newHttpClient();
// criando a requisição
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://viacep.com.br/ws/" + cep + "/json/")).build();
// criando o response
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
// utilizando o jackson
ObjectMapper mapper = new ObjectMapper();
addressDto = mapper.readValue(response.body(), AddressDto.class);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return addressDto;
}
}
Код: Выделить всё
Class Main
public class Main {
public static void main(String[] args) {
ApiService apiService = new ApiService();
try {
AddressDto addressDto = apiService.getEndereco("03107040");
System.out.println(addressDto.getCep());
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... stantiated