Http Get & Post & JSON - rlip/java GitHub Wiki

Rest template

       RestTemplate restTemplate = new RestTemplate();
        Book obj = restTemplate.getForObject("https://mocki.io/v1/4ab3e12e-7ab6-4b3b-b476-d9629d67f6c7", Book.class);


        //tak zmapuje do mapy (jak nie znamy nazwy, albo dużo ich)
        ParameterizedTypeReference<HashMap<String, Stock>> responseType = new ParameterizedTypeReference<HashMap<String, Stock>>() {};

        RequestEntity<Void> request = RequestEntity.get(URI.create("https://mocki.io/v1/4ab3e12e-7ab6-4b3b-b476-d9629d67f6c7"))
                .accept(MediaType.APPLICATION_JSON).build();
        Map<String, Stock> jsonDictionary = restTemplate.exchange(request, responseType).getBody();
        

PUT

    static final Proxy proxyTest = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.4", 3128));

    public static void main(String[] args) throws Exception {
        OkHttpClient.Builder builder = new OkHttpClient.Builder().proxy(proxyTest);
        OkHttpClient client = builder.build();

        RequestBody body = new FormBody.Builder()
                .add("id", "1")
                .add("title", "foo")
                .add("body", "bar")
                .add("userId", "1")
                .build();

        Headers headers = new Headers.Builder().add("Content-type", "application/json; charset=UTF-8").build();
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .headers(headers)
                .method("PUT", body)
                .build();

        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }

GET

public class GetApp {

    static final Gson gson = new Gson();
    static final Type type = new TypeToken<List<Cloth>>() {
    }.getType();
    static final Proxy proxyTest = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.4", 3128));

    public static void main(String[] args) throws Exception {
        printJsonSyncByURL();
        printJsonSyncByOkHttpClient();
        printJsonAsyncByOkHttpClient();
    }

    private static void printJsonSyncByURL() throws IOException {
        URL url = new URL("https://next.json-generator.com/api/json/get/VyvzEVv0I");
        List<Cloth> clothList = gson.fromJson(new BufferedReader(new InputStreamReader(url.openConnection(proxyTest).getInputStream())), type);
        clothList.stream().forEach(System.out::println);
    }

    private static void printJsonSyncByOkHttpClient() throws IOException {
        OkHttpClient.Builder builder = new OkHttpClient.Builder().proxy(proxyTest);
        OkHttpClient client = builder.build();
        Request request = new Request.Builder()
                .url("https://next.json-generator.com/api/json/get/VyvzEVv0I") //json
                .build();
        Response response = client.newCall(request).execute();
        String data = response.body().string();
        List<Cloth> clothList = gson.fromJson(data, type);
        clothList.stream().forEach(System.out::println);
    }

    private static void printJsonAsyncByOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder().proxy(proxyTest);
        OkHttpClient client = builder.build();
        Request request = new Request.Builder()
//                .url("https://next.json-generator.com/api/json/get/VyvzEVv0I") //json
                .url("https://countwordsfree.com/download/xml/60c83afe-48e3-4786-9172-83fc66c96bc9") //xml
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();

                //json
//                Type type = new TypeToken<List<Cloth>>(){}.getType();
//                List<Cloth> clothList = gson.fromJson(data, type);
//                clothList.stream().forEach(System.out::println);

                // xml
                Serializer serializer = new Persister();
                try {
                    Cloth cloth = serializer.read(Cloth.class, data);
                    System.out.println(cloth);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(Call call, IOException e) {
                System.out.println("ERROR: " + toString());
            }
        });
    }
}

POM

    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>3.11.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
    </dependency>
    <dependency>
      <groupId>org.simpleframework</groupId>
      <artifactId>simple-xml</artifactId>
      <version>2.7.1</version>
    </dependency>

JSON

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Autowire
ObjectMapper objectMapper;

            try {
                JsonNode jsonObject = objectMapper.readTree(response.getBody());
                final String description = jsonObject.get("error").get("description").asText();
                if ("Invalid input: msisdn".equals(description)) {
                    throw new InvalidMsisdnException(configurationService.getErrorMessage(InvalidMsisdnException.NAME));
                }
            } catch (JsonProcessingException e) {
                log.error("Error parsing response", e);
                throw new InvalidMsisdnException(configurationService.getErrorMessage(InvalidMsisdnException.NAME));
            }
⚠️ **GitHub.com Fallback** ⚠️