Get OuputStream for Request Body with Jersey Client?

I will not host the CSV file in a web service using the jersey client without having to store the contents of the csv in memory.

So, I started with some code like this:

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

I would like to avoid buffering all the CSV content in memory before sending it to the server, I know that I can send the File object using the client, and the jersey will concern downloading and sending the file, however in this case CSV content will be generated automatically, so I I would really like to just write it in an OutputStream, which goes directly to the server, and not to the memory ... is there a way I can do this using the Jersey client?

+3
source share
1

, OutputStream, , , .

InputStream post WebResource, , , .

CSV ResultSet, , 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;

 }

}
+1

Source: https://habr.com/ru/post/1772617/


All Articles