1

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

我从雅虎财经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

看看是否有帮助:http://developer.yahoo.com/search/rest.html。 –

回答

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); 
+0

感谢您的支持!当我编译它时,它给了我无法识别的符号错误。也许我包括错误的jar文件?我目前在编译期间将httpclient-4.3.1.jar添加为类路径。有什么建议么? – user3163760

+0

这取决于这些符号是什么,但我想你错过了其他直接依赖或传递依赖(直接依赖关系所需的jar文件)。你应该使用像Maven或Gradle这样的构建工具来帮助你管理它。 – Vidya

+0

所以我应该引用这里列出的所有依赖关系? http://mvnrepository.com/artifact/commons-httpclient/commons-httpclient/3.1 – user3163760