这是我在javaFX中的第二个项目,所以我被连接卡住了。我尝试连接到URL,但不确定是否正确。
在网上找到的一个项目中,一个类中存在连接,而控制器中的其余代码则以这种方式编写,因此现在我得到的GUI仅来自System.out.println
,而没有任何结果。
但是,当我将代码放在类Main
中时,我得到了所有结果。
我想在一个类中建立连接,在另一个类中建立控制器,所以,请告诉我到目前为止我的代码有什么错。
这是控制者:
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();
}
}
这是URLconnection类:
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;
}
}
答案 0 :(得分:2)
为什么要重新发明轮子(如果已经存在)?尝试使用Unirest
System.out.println( Unirest.get( "http://api.hnb.hr/" )
.asJson()
.getBody()
.toString()
);
请注意,http://api.hnb.hr/
将返回网站页面视图。也许尝试请求实际的API,例如http://api.hnb.hr/tecajn/v1
。