Created
August 23, 2013 02:26
-
-
Save pdeva/6314946 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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