DevShivmohan / Learning-everything

Learning for developer only
0 stars 1 forks source link

API call via javascript and simple java networking #16

Open DevShivmohan opened 1 year ago

DevShivmohan commented 1 year ago

API call through javascript

<script>
            function apiCall(){
                console.log("Shiv executed");
                var xhr = new XMLHttpRequest();
                var url = "http:localhost:8090/razorpay/save";
                xhr.open("POST", url, true);
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        console.log("Success response");
                        var json = JSON.parse(xhr.responseText);
                        console.log(json);
                        console.log(json.email + ", " + json.password);
                    }else{
                        console.log("Error response");
                    }
                };
                var data = JSON.stringify({"o_id": "hey@mail.com", "p_id": "101010","status":"Success"});
                xhr.send(data);
            }
        </script>
rahulbansal3005 commented 1 year ago

hi i am interested to work on this issue

DevShivmohan commented 5 months ago

SImple API call using java networking

Used google gson library

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
package com.shiv.exception;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class OnlineTest {
    public static void main(String[] args) throws Throwable {
        System.out.println("Discounted price = " + discountedPrice(74001795));
        System.out.println("Discounted price = " + discountedPrice(740017));
    }

    /**
     * Call an API using simple java net
     * And gson library to convert response into object
     * @param barcode
     * @return
     * @throws Throwable
     */
    public static int discountedPrice(int barcode) throws Throwable {
        URL url = new URL("https://jsonmock.hackerrank.com/api/inventory?barcode=" + barcode);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("accept", "application/json");
        httpURLConnection.setRequestMethod("GET");
        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode != 200)
            return -1;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        bufferedReader.close();
        Gson gson = new Gson();
        DataList dataList = gson.fromJson(stringBuilder.toString(), DataList.class);
        System.out.println(dataList);
        if (dataList.getData().isEmpty())
            return -1;
        Data data = dataList.getData().get(0);
        return (int) (data.getPrice() - ((data.getDiscount() / 100) * data.getPrice()));
    }

}

class DataList {
    private double page;
    private double per_page;
    private double total;
    private double total_pages;
    private List<Data> data;

    public double getPage() {
        return page;
    }

    public void setPage(double page) {
        this.page = page;
    }

    public double getPer_page() {
        return per_page;
    }

    public void setPer_page(double per_page) {
        this.per_page = per_page;
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public double getTotal_pages() {
        return total_pages;
    }

    public void setTotal_pages(double total_pages) {
        this.total_pages = total_pages;
    }

    public List<Data> getData() {
        return data;
    }

    public void setData(List<Data> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "DataList{" +
                "page=" + page +
                ", per_page=" + per_page +
                ", total=" + total +
                ", total_pages=" + total_pages +
                ", data=" + data +
                '}';
    }
}

class Data {
    private String barcode;
    private String item;
    private String category;
    private double price;
    private double discount;
    private double available;

    @Override
    public String toString() {
        return "Data{" +
                "barcode='" + barcode + '\'' +
                ", item='" + item + '\'' +
                ", category='" + category + '\'' +
                ", price=" + price +
                ", discount=" + discount +
                ", available=" + available +
                '}';
    }

    public String getBarcode() {
        return barcode;
    }

    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public double getDiscount() {
        return discount;
    }

    public void setDiscount(double discount) {
        this.discount = discount;
    }

    public double getAvailable() {
        return available;
    }

    public void setAvailable(double available) {
        this.available = available;
    }
}
DevShivmohan commented 5 months ago

Simple API call using java networking and convert response into object using google simple json library

json-simple Library

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Code

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiCaller {

    public static void main(String[] args) {
        try {
            // Specify the API endpoint URL
            URL url = new URL("https://api.example.com/data");

            // Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set the request method (GET, POST, etc.)
            connection.setRequestMethod("GET");

            // Get the response code
            int responseCode = connection.getResponseCode();

            // Check if the request was successful (HTTP 200 OK)
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Read the response from the API
                InputStreamReader in = new InputStreamReader(connection.getInputStream());

                // Parse the JSON response using JSON.simple
                JSONParser parser = new JSONParser();
                JSONObject jsonResponse = (JSONObject) parser.parse(in);

                // Extract the 'data' array from the response
                JSONArray dataArray = (JSONArray) jsonResponse.get("data");

                // Iterate through the array and convert each JSON object to a Java object
                for (Object dataObj : dataArray) {
                    JSONObject data = (JSONObject) dataObj;

                    // Convert JSON fields to Java fields
                    long barcode = (Long) data.get("barcode");
                    String item = (String) data.get("item");
                    String category = (String) data.get("category");
                    double price = (Double) data.get("price");
                    double discount = (Double) data.get("discount");
                    double available = (Double) data.get("available");

                    // Create a custom Java object
                    Data responseObject = new Data(barcode, item, category, price, discount, available);

                    // Now you can use the 'responseObject' as a Java object
                    System.out.println(responseObject);
                }
            } else {
                System.out.println("Error: " + responseCode);
            }

            // Close the connection
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Data {
    long barcode;
    String item;
    String category;
    double price;
    double discount;
    double available;

    public Data(long barcode, String item, String category, double price, double discount, double available) {
        this.barcode = barcode;
        this.item = item;
        this.category = category;
        this.price = price;
        this.discount = discount;
        this.available = available;
    }

    @Override
    public String toString() {
        return "Data{" +
                "barcode=" + barcode +
                ", item='" + item + '\'' +
                ", category='" + category + '\'' +
                ", price=" + price +
                ", discount=" + discount +
                ", available=" + available +
                '}';
    }
}