2011-03-20 61 views
1

嗨我一直在試圖從http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2下載csv,並一直試圖隨後解析數據。以下是代碼。它目前只返回吐司中的html頭部。任何想法,爲什麼它不是在csv中返回實際結果?HttpClient返回錯誤的csv?

Stock stock = new Stock(); 
    try { 

     //need to call yahoo api and get csv -> parse csv for most recent price and price change 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     HttpGet httpGet = new HttpGet(uri); 
     HttpResponse response = httpClient.execute(httpGet, localContext); 
     String result = ""; 

     BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

     String line = ""; 
     while ((line = reader.readLine()) != null){ 

       result += line + "\n"; 
       String[] RowData = result.split("\n"); 
       Toast.makeText(this, result, Toast.LENGTH_LONG).show(); 
       String name = RowData[0]; 
       String price = RowData[1]; 
       String change = RowData[2]; 

       stock.setPrice(Double.parseDouble(price)); 
       stock.setTicker(name); 
       stock.setChange(change); 


      } 

回答

3

難道你不需要以逗號而不是換行符來輸入split

String[] RowData = result.split(","); 

當我與

System.out.println("result = "+ result); 

運行使用上述,並更換吐司的代碼我得到:

result = "MSFT",24.80,"+0.08%" 

namepricechange值被成功地填充。我根本看不到標題行。

請注意,Java約定是變量名以小寫字母開頭,所以rowData不是RowData

+0

是的,這是解決方案。弄明白了:)。我還需要使用replaceAll來擺脫引號。 – locoboy 2011-03-20 21:10:44

0
http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2 

您提供的含有兩個參數的網址:

1: s=msft 
    -this is the yahoo finance api code for microsoft 

2: f=sl1p2 
    - this contains 3 sub-parameters 
    - s [it is the company name] 
    - l1 [it is the company's last quote price] 
    - p2 [it is the price change] 

,所以我想你所得到的CSV是正確的。

+0

是啊我不完全確定我要去哪裏錯了。 – locoboy 2011-03-20 18:14:40

+1

我有一個相同的php代碼片段。如果你想,那麼我可以與你分享。 – 2011-03-20 18:18:28

+0

當然我想看看 – locoboy 2011-03-20 18:55:27

0
<?php 

function getStockSite($stockLink){ 

    if ($fp = fopen($stockLink, 'r')) { 
     $content = ''; 

     while ($line = fread($fp, 1024)) { 
     $content .= $line; 
     } 
    } 

    return $content; 
} 

?> 

<table cellpadding="0" style="width:700px;" cellspacing="0"> 

<tr> 
<th>Country</th> 
<th>Indices</th> 
<th>Date</th> 
<th>Price</th> 
<th>Prev. Price</th> 
<th>High</th> 
<th>Low</th> 
<th>Change</th> 
</tr> 


<?php 

$url="http://finance.yahoo.com/d/quotes.csv?s=^BSESN&f=d1p5phgc6"; 
try 
{ 
$data = getStockSite($url); 
$bse=explode(",",$data); 
} 
catch(exception $e) 
{ 
} 
?> 

<tr> 
<td>INDIA</td> 
<td>SENSEX</td> 
<td><?php echo $bse[0];?></td> 
<td><?php echo $bse[1];?></td> 
<td><?php echo $bse[2];?></td> 
<td><?php echo $bse[3];?></td> 
<td><?php echo $bse[4];?></td> 
<td><?php echo $bse[5];?></td> 
<tr> 


</table>