Json 如何使flatter能够查看要求不同变量访问它们的更难的API?
例如,我希望创建一些可以获得流量更新的东西,但dataMall集合只提供python变量,而不是.dart或.java变量 这是我写下的代码:Json 如何使flatter能够查看要求不同变量访问它们的更难的API?,json,api,flutter,dart,Json,Api,Flutter,Dart,例如,我希望创建一些可以获得流量更新的东西,但dataMall集合只提供python变量,而不是.dart或.java变量 这是我写下的代码: void getData() async { http.Response response= await http.get( 'http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=83139'); print(response
void getData() async {
http.Response response= await http.get(
'http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=83139');
print(response.body);
}
这是他们用python编写的代码
import urllib
from urlparse import urlparse
import httplib2 as http #External library
if __name__=="__main__":
#Authentication parameters
headers = { 'AccountKey' : 'ACCOUNT_KEY',
'accept' : 'application/json'} #this is by default
#API parameters
uri = 'http://datamall2.mytransport.sg/' #Resource URL
path = '/ltaodataservice/BusRoutes?'
#Build query string & specify type of API call
target = urlparse(uri + path)
print target.geturl()
method = 'GET'
body = ''
#Get handle to http
h = http.Http()
#Obtain results
response, content = h.request(
target.geturl(),
method,
body,
headers)
#Parse JSON to print
jsonObj = json.loads(content)
print json.dumps(jsonObj, sort_keys=True, indent=4)
#Save result to file
with open("bus_routes.json","w") as outfile:
#Saving jsonObj["d"]
json.dump(jsonObj, outfile, sort_keys=True, indent=4,
ensure_ascii=False)
您需要在请求的标题中传递AccountKey
return http.get('http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=83139', headers: {
'Accept': 'application/json',
'AccountKey': 'YOUR_PRIVATE_KEY'
});
根据
http
package的文档,get
函数有一个命名参数headers
另外,在第1节下。在您提供的pdf中进行API调用
在标题下输入AccountKey
默认的响应主体将是JSON。您可以通过在标题中添加accept:'application/atom+xml'
来更改此设置。这是可选的
pdf中提供的示例代码是python,但您得到的响应将是JSON
所以你只需要
void getData() async {
http.Response response= await http.get('http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=83139', headers: {
'AccountKey': 'YOUR_PRIVATE_KEY'
});
print(response.body);
}
然后可以解析响应体。是颤振网站上的一个示例。你能解释一下这个答案是如何解决问题的,而不是只发布代码答案。哦,谢谢:))。不过,我还有一个问题,例如:;如果我想将一个位置返回到API,是否可能,或者它是否使用与上面所示相同的格式;假设要找出离所述用户最近的公共汽车站:如果要向API提供一些数据,您需要一个POST
请求。但是如果它根据您发送的值返回一些信息,它将是GET
request。所以这里看起来像是get
request。最好看看文件。