上题目:
计划从接口读取数据后,存储到本地Json文件,以后先从本地读。
涉及到3个知识点:
- 利用http协议从远程调度接口,并读取数据。
- 把数据存储到本地硬盘。
- 从本地硬盘读取json 字段后做查询操作。
python 版本:
import json
import requests
def get_currency():
YOUR_APP_ID = "1e5855e44a3f41638b2350ab08d31297"
url = "https://openexchangerates.org/api/latest.json?app_id={0}".format(YOUR_APP_ID)
response = requests.get(url)
content = response.json()
return content
def store_json_tolocal(content):
cache_path = "./currency.json"
with open(cache_path,"w",encoding="utf-8") as f:
jsonstr = json.dumps(content)
f.write(jsonstr)
return None
def get_json_fromlocal():
cache_path=("./currency.json")
with open(cache_path,"r",encoding="utf-8") as f:
result = f.read()
return result
def question_and_answer():
euros = input("How many euros are you exchanging")
print("What is the exchange rate?")
result = get_json_fromlocal()
exchangerate = json.loads(result)['rates']['EUR']
print("The currency should be {0}".format(exchangerate))
print("{0} euros at an exchange rate of {1} is \n {2} U.S. dollars".format(euros,exchangerate,float(euros)/float(exchangerate)))
#content = get_currency() 仅仅需要运行一次,从接口度数据
#store_json_tolocal(content) 仅仅需要运行一次,缓存到本地
#result= get_json_fromlocal() debug
#print(type(result)) debug
#print(result) debug
#print(json.loads(result)) debug
question_and_answer()
上面get_currency()函数只运行一次,产生本地文件 currency.json
以后从这个文件夹下读取即可:
运行效果图:
java 版本,感觉复杂了好多:
首先使用vscode创建一个java 项目,把相关的jar包从网上下载:
- 从https://hc.apache.org/httpcomponents-client-4.5.x/download.html 下载jar包
下载jar 包后,把相关文件挪到 java 项目lib 文件夹下
2.从https://mvnrepository.com/artifact/com.alibaba/fastjson/1.2.59 下载fastjson包,
并把jar 包挪到lib 文件夹下:
挪完后效果如下:
App.java 脚本:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson. *;
import java.util.Scanner;
/ **
*发送 get请求
* /
public class App {
private String exchangerate;
// 从公网中读取数据,并打印出来内容,同时把返回的json字段存储到exchangerate上
public void get() {
String YOUR_APP_ID = "1e5855e44a3f41638b2350ab08d31297";
String url = "https://openexchangerates.org/api/latest.json?app_id="+YOUR_APP_ID;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet(url);
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
this.exchangerate = EntityUtils.toString(entity);
System.out.println("Response content: " + this.exchangerate);
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch(ClientProtocolException
e) {
e.printStackTrace();
} catch(ParseException
e) {
e.printStackTrace();
} catch(IOException
e) {
e.printStackTrace();
} finally {
// 关闭连接, 释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 从本地内存读取exchangerate数据,并把把数据写到本地,
public void WritetoLocal()
{
File usdrate = new File("./usdrate.json");
if (usdrate.exists())
{
System.out.println("文件存在");
}
else {
try {
usdrate.createNewFile();
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("文件创建成功");
}
try{
FileOutputStream fileOutputStream = new FileOutputStream(usdrate);
fileOutputStream.write(this.exchangerate.getBytes());
fileOutputStream.close();
System.out.println("json 数据保存成功!");
}catch(Exception e){
e.printStackTrace();
}
}
// 从本地文件夹读取usdrate.json,并返回一个字符串
public String GetLocaldata()
{
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader("./usdrate.json"));
String s = null;
while ((s = br.readLine()) != null){
result.append(System.lineSeparator()+s);
}
br.close();
}catch(Exception e)
{
e.printStackTrace();
}
return result.toString();
}
String readJson(String jsonstring, String countrycode)
{
// 用countrycode 从json string 找数据
Rates newRates = JSON.parseObject(jsonstring, Rates.class );
String countryrate= newRates.GetEurorate(countrycode);
return countryrate;
}
void QustionsandAnswers()
{
System.out.println("How much money are you exchanging?");
Scanner sc = new Scanner(System. in);
String eurosstr = sc.next();
System.out.println("Please input the country code");
String countrycode = sc.next();
System.out.println("What is the exchange rate?");
String countryrate = this.readJson(this.GetLocaldata(), countrycode);
System.out.println(eurosstr + " at an exchange rate of " + countryrate + " is ");
float result = Float.parseFloat(eurosstr) / Float.parseFloat(countryrate);
System.out.println(result + " U.S. dollars.");
}
public static void main(String[] args) throws Exception
{
App lesson10 = new App();
// lesson10.get(); 只需要运行一次,从外地读数据到本地并缓存到json
// lesson10.WritetoLocal(); 只需要运行一次,把jso 缓存到本地硬盘
// 每次都需要运行,从本地盘读取映射表数据
//String result = lesson10.GetLocaldata();
// 展示映射表数据
//System.out.println("result is " + result);
// 找到对应的国家 / 地区汇率
// String countryrate = lesson10.readJson(result, "EUR");
// 返回找到的对应的汇率
// System.out.println("对应国家的汇率为" + countryrate);
lesson10.QustionsandAnswers();
}
}
Rates.java 脚本:
import java.util.List;
import java.util.OptionalInt;
import java.util.stream. *;
import java.util.HashMap;
public class Rates{
private String disclamer;
private String license;
private String timestamp;
private String base;
private HashMap < String, String > rates;
public Rates(String disclaimer, String license, String timestamp, String base, HashMap < String, String > rates)
{
this.disclamer = disclaimer;
this.license = license;
this.timestamp = timestamp;
this.base = base;
this.rates = rates;
}
// 标准getters 和 setters.
String GetEurorate(String EUR )
{
String info = this.rates.get(EUR);
System.out.println(info);
return info;
}
}
这里几个知识点:
从json 读取数据到本地用到了阿里的fastjson 包,支持按照对象的格式来解析json,
Rates newRates = JSON.parseObject(jsonstring, Rates.class );
这里Rate类,单独设置了一个HashMap() 作为它的字段,通过 HashMap().get()方法来获取对应的国家的汇率。
fast json 的使用:
参考:https://www.runoob.com/w3cnote/fastjson-intro.html
hash map的使用,
参考:https://www.runoob.com/java/java-hashmap.html
运行效果图: