user8616404
user8616404

Reputation:

Connection with public API

This is my second project ever in javaFX so I am stuck with no result from connection. I tried to connect to URL and not very sure if I am doing it right.
In one project which I found on the net, there is connection in one class, and the rest of the code in controller, so I writen in that way, and now I get just my GUI without any result from System.out.println. But, when I put my code in class Main, I get all the result. I would like to have connection in one class and controller in other, so, please tell me what did I do wrong in my code so far.

This is controller:

package pretvaracValuta;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ResourceBundle;


public class PretvaracController implements Initializable {

    private URLconnection uc;

    public void initialize(URL url, ResourceBundle rb) {
        uc = new URLconnection();
    }


    public void connection() {
        HttpURLConnection conn = uc.urlConnect();

        try {   

            int responseCode = conn.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            System.out.println("Broj tečajnice = "+ responseCode);
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);

                System.out.println(response.toString());
            }
            in.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        connection();

    }
}

This is URLconnection class:

package pretvaracValuta;

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

public class URLconnection {

public HttpURLConnection urlConnect() {

    try {   

        URL obj = new URL("http://api.hnb.hr/");

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        return con;
        }

        catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}

Upvotes: 0

Views: 127

Answers (1)

Jaquarh
Jaquarh

Reputation: 6693

Why reinvent the wheel if it already exists? Try using Unirest

System.out.println( Unirest.get( "http://api.hnb.hr/" )
                           .asJson()
                           .getBody()
                           .toString()
);

Note, http://api.hnb.hr/ is returning a website page view. Maybe try requesting the actual API like http://api.hnb.hr/tecajn/v1.

Here is a link to the Maven dependency.

Upvotes: 2

Related Questions