我正在尝试从外部 API 获取 JSON 并解析它,以便我可以访问 JSON 对象值,以避免我不需要的值(字段)。
我已经研究了一点 JSONOBject 库并解析了对象,但是,感觉我做了太多的硬编码并且根本没有正确执行,非常感谢反馈。
用户输入后输出结果:
发送“GET”请求到 URL: https: //api.coindesk.com/v1/bpi/currentprice/(用户输入货币)
数据在 UTC 时间/日期获取:2019 年 9 月 17 日 22:51:00 UTC 说明:乌克兰格里夫纳汇率浮动:253737.6633
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class App {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the currency you would like to get BTC current rate for");
String userInput = in.readLine();
try {
String url = "https://api.coindesk.com/v1/bpi/currentprice/" + userInput;
URL obj = new URL(url);
// HttpURLConnection instance is making a request
//openConnection() method of URL class opens the connection to specified URL
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// saving the response code from the request
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("---------------------------------------------");
System.out.println("Response Code from the HTTP request : " + responseCode);
System.out.println("---------------------------------------------");
}
饮歌长啸
相关分类