gpt4 book ai didi

java - 使用 Yahoo Finance API 检索股票行情

转载 作者:太空宇宙 更新时间:2023-11-04 15:15:00 26 4
gpt4 key购买 nike

我正在尝试为最终项目构建一个简单的幻想股票 JAVA 应用程序。目前的主要问题是弄清楚如何检索股票数据。

我从雅虎财经 Java 教程中获取了这段代码,但它似乎已经过时了。有人愿意帮助我并更新 httpclient 4.x 或将我链接到一个有效的示例吗?

另外,在命令行中,我是否只需在 -cp 中引用 httpclient,或者也引用 httpcore?

import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class YahooWebServiceGet {

public static void main(String[] args) throws Exception {
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=umbrella&results=10";

HttpClient client = new HttpClient();
GetMethod method = new GetMethod(request);

// Send GET request
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
InputStream rstream = null;

// Get the response body
rstream = method.getResponseBodyAsStream();

// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}

}

最佳答案

尝试这样的事情:

CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=umbrella&results=10";
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();

//do stuff with is
} finally {
response.close();
}

我不熟悉 Yahoo Finance API,但如果响应是 JSON 并且您喜欢使用 Jackson,则可以使用 InputStream 执行此操作:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(inputStream, Map.class);

关于java - 使用 Yahoo Finance API 检索股票行情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20940769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com