2010-06-14 69 views

回答

18

这很容易在任何语言,但机制各不相同。随着wget和一个shell:

wget 'http://search.twitter.com/search.json?q=hi' -O hi.json 

要追加:

wget 'http://search.twitter.com/search.json?q=hi' -O - >> hi.json 

使用Python:

urllib.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json') 

要追加:

hi_web = urllib2.urlopen('http://search.twitter.com/search.json?q=hi'); 
with open('hi.json', 'ab') as hi_file: 
    hi_file.write(hi_web.read()) 
+0

然后我会如何在EOF上添加更多更新? – Skizit 2010-06-14 21:10:18

2

在外壳:

wget -O output.json 'http://search.twitter.com/search.json?q=hi' 
+0

然后,我会如何向EOF添加更多更新? – Skizit 2010-06-14 21:09:50

+0

只需输出到标准输出('-')并使用追加重定向操作符('>>')。 – 2010-06-14 21:15:37

+1

'wget >> output.json' – Ether 2010-06-14 21:16:12

4

这里的(详细))的Java变种:

InputStream input = null; 
OutputStream output = null; 
try { 
    input = new URL("http://search.twitter.com/search.json?q=hi").openStream(); 
    output = new FileOutputStream("/output.json"); 
    byte[] buffer = new byte[1024]; 
    for (int length = 0; (length = input.read(buffer)) > 0;) { 
     output.write(buffer, 0, length); 
    } 
    // Here you could append further stuff to `output` if necessary. 
} finally { 
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {} 
    if (input != null) try { input.close(); } catch (IOException logOrIgnore) {} 
} 

参见:

+0

然后,我会如何将更多更新附加到EOF? – Skizit 2010-06-14 21:11:03

+0

请参阅代码示例中的注释。 – BalusC 2010-06-14 21:11:38

3

您可以使用CURL

curl -d "q=hi" http://search.twitter.com -o file1.txt 
4

在PHP:

$outfile= 'result.json'; 
$url='http://search.twitter.com/search.json?q=hi'; 
$json = file_get_contents($url); 
if($json) { 
    if(file_put_contents($outfile, $json, FILE_APPEND)) { 
     echo "Saved JSON fetched from “{$url}” as “{$outfile}”."; 
    } 
    else { 
     echo "Unable to save JSON to “{$outfile}”."; 
    } 
} 
else { 
    echo "Unable to fetch JSON from “{$url}”."; 
} 
1

您可以使用Jackson

ObjectMapper mapper = new ObjectMapper(); 
Map<String,Object> map = mapper.readValue(url, Map.class); 
mapper.writeValue(new File("myfile.json"), map); 
1

下面是用PHP和F打开这样做的另一种方式。

<?php 
// Define your output file name and your search query 
$output = 'result.txt'; 
$search = 'great'; 

write_twitter_to_file($output, $search); 

/* 
* Writes Json responses from twitter API to a file output. 
* 
* @param $output: The name of the file that contains the output 
* @param $search: The search term query to use in the Twitter API 
*/ 

function write_twitter_to_file($output, $search) { 
    $search = urlencode($search); 
    $url = 'http://search.twitter.com/search.json?q=' . $search; 
    $handle = fopen($url, "r"); 

    if ($handle) { 
     while (($buffer = fgets($handle, 4096)) !== false) { 
      file_put_contents($output, $buffer, FILE_APPEND); 
      echo "Output has been saved to file<br/>"; 
     } 

     if (!feof($handle)) { 
      echo "Error: unexpected fgets() fail\n"; 
     } 

     fclose($handle); 
    } 

} 
?>