Skip to content

Instantly share code, notes, and snippets.

@pdeva
Created August 23, 2013 02:26
Show Gist options
  • Save pdeva/6314946 to your computer and use it in GitHub Desktop.
Save pdeva/6314946 to your computer and use it in GitHub Desktop.
/**
* @author Prashant Deva
*/
public class ConnectionDataWriter
{
static class ConnectorHttpException extends HttpRequest.HttpRequestException
{
ConnectorHttpException(IOException cause)
{
super(cause);
}
}
private static final String UTF_8 = "UTF-8";
static void writeData(HttpRequest httpRequest, boolean compressed, JSONStreamAware data)
{
if (compressed)
httpRequest.header("CONTENT-ENCODING", "deflate");
try
{
writeData(httpRequest.getConnection(), compressed, data);
} catch (IOException e)
{
throw new ConnectorHttpException(e);
}
}
private static OutputStream getOutputStream(HttpURLConnection conn, boolean isDeflate) throws IOException
{
conn.setDoOutput(true);
if (isDeflate)
return new DeflaterOutputStream(conn.getOutputStream(), new Deflater(-1));
return conn.getOutputStream();
}
private static void writeData(HttpURLConnection conn, boolean isDeflate, JSONStreamAware obj) throws IOException
{
Writer out = null;
try
{
OutputStream os = getOutputStream(conn, isDeflate);
out = new OutputStreamWriter(os, UTF_8);
obj.writeJSONString(out);
out.flush();
} finally
{
if (out != null)
out.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment