Question

I am trying to build a simple fantasy stocks JAVA application of sorts for a final project. The main problem as of now is figuring out how to retrieve the stock data.

I took this snippet of code from the Yahoo Finance Java tutorials, but it seems to be outdated. Would anyone be willing help me out and update this for httpclient 4.x or link me to an example that works?

Also, in command line, would I only have to reference httpclient in -cp, or httpcore as well?

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();
    }

}
Was it helpful?

Solution

Try something like this:

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();
}

I am unfamiliar with the Yahoo Finance API, but if the response is JSON and you are cool with using Jackson, you can do this with the InputStream:

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

OTHER TIPS

The Yahoo quote service has gone away. Try the Investor's Exchange API instead.

Its quite simple. Do the following - Add the following maven dependency to your pom.xml

<dependency>
    <groupId>com.yahoofinance-api</groupId>
    <artifactId>YahooFinanceAPI</artifactId>
    <version>3.15.0</version>
</dependency>

and then in the java class, you wish to use, type the following to get stock data

 YahooFinance.get("GOOG")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top