2010-11-02 61 views
3

我wan't發佈一個CSV文件使用新澤西客戶端的Web服務,而無需在內存中緩衝CSV內容。使用Jersey客戶端獲取OuputStream到請求主體?

於是我開始用類似這樣的代碼:

String csvContent = [the buffered CSV content]; 
Client c = Client.create(); 
WebResource r = c.resouce("http://example.com/services/service"); 
r.type("text/csv").post(csvContent); 

我想避免發送給服務器之前緩存在內存中的整個CSV內容,我知道我可以給一個文件對象使用客戶端和球衣將處理負荷和發送文件,但是在這種情況下,CSV內容將被自動生成所以我真的很想做的僅僅是簡單地將其寫入到直接進入服務器的OutputStream而不是進入內存......有沒有一種方法可以使用Jersey客戶端來做到這一點?

回答

1

看起來澤西不支持直接寫入OutputStream,但經過多次挖掘和合並後,我學到了一些不同的想法,我設法學到了這門課。

澤西支持通過一個InputStream插入WebResource柱方法,其讀取和寫入請求主體的內容。

我正在從ResultSet生成一個CSV文件,因此我編寫了一個擴展InputStream的類,並且在調用read()時,它從ResultSet獲取一條記錄並構建一行CSV文件,並返回一個來自線。每次調用read()時,都會返回下一個字符,直到整行返回,此時將從數據庫中讀取下一條記錄,並重復該過程,直到沒有記錄爲止。

我使用了一個名爲OpenCSV建庫中的CSV的文件行

public class ResultSetCsvInputStream extends InputStream { 

private ResultSet rs; 
private int columns; 

private int ch; 
private byte[] line; 

/** 
    * Construct a new SchemaInputStream 
    * @param rs 
    * @throws SQLException 
    */ 
public ResultSetCsvInputStream(ResultSet rs) throws SQLException { 

    this.rs = rs; 

    // write column names 
    ResultSetMetaData meta = rs.getMetaData(); 
    columns = meta.getColumnCount(); 
    String[] colNames = new String[columns]; 
    for(int i = 0; i < colNames.length; i++) { 
    colNames[i] = meta.getColumnName(i+1); 
    } 
    writeLine(colNames); 

} 

private void writeLine(String[] ln) { 
    StringWriter strWriter = new StringWriter(); 
    CSVWriter csv = new CSVWriter(strWriter); 
    csv.writeNext(ln); 
    line = strWriter.toString().getBytes(Charset.forName("UTF8")); 
    ch = 0; 
} 

@Override 
public int read() throws IOException { 

    if(rs == null) 
    return -1; 

    // read the next line 
    if(line == null || ch >= line.length) { 

    // query next line 
    try { 
    if(rs.next()) { 
    String[] record = new String[columns]; 
    for(int i = 0; i < record.length; i++) { 
     record[i] = rs.getString(i+1); 
    } 
    writeLine(record); 
    } 
    else { 
    rs = null; 
    return -1; 
    } 
    } catch (SQLException e) { 
    throw new IOException(e); 
    } 

    } 

    // read next character 
    return line[ch++] & 0xFF; 

} 

} 
相關問題