我正在尝试为最终项目构建一个简单的幻想股票JAVA应用程序。目前的主要问题是弄清楚如何检索库存数据。
我从Yahoo Finance Java教程中获取了这段代码,但似乎已经过时了。有没有人愿意帮助我并为httpclient 4.x更新此内容或将我链接到一个有效的示例?
另外,在命令行中,我只需要在-cp或httpcore中引用httpclient吗?
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();
}
}
答案 0 :(得分:0)
尝试这样的事情:
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();
}
我对雅虎财经API不熟悉,但如果回复是JSON并且你使用杰克逊很酷,你可以使用InputStream
执行此操作:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(inputStream, Map.class);
答案 1 :(得分:0)
雅虎报价服务已经消失。请改为使用Investor's Exchange API。
答案 2 :(得分:0)
其实很简单。请执行下列操作 - 将以下 maven 依赖项添加到您的 pom.xml
<dependency>
<groupId>com.yahoofinance-api</groupId>
<artifactId>YahooFinanceAPI</artifactId>
<version>3.15.0</version>
</dependency>
然后在要使用的java类中,键入以下内容以获取股票数据
YahooFinance.get("GOOG")