Skip to content

Commit 8c3e4de

Browse files
committed
Merge pull request #23 from SvenWoltmann/master
When sending data to the API, data string should be converted to byte array only once
2 parents e597d6d + 52a631d commit 8c3e4de

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

libs/sparkpost-lib/src/main/java/com/sparkpost/transport/RestConnection.java

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -167,14 +167,19 @@ private HttpURLConnection createConnectionObject(String path, Method method) thr
167167

168168
// Send HTTP data (payload) to server
169169
private void sendData(HttpURLConnection conn, String data) throws SparkPostException {
170-
String lenStr;
171-
try {
172-
lenStr = Integer.toString(data.getBytes(DEFAULT_CHARSET).length);
173-
} catch (UnsupportedEncodingException e) {
170+
byte[] bytes = null;
171+
try
172+
{
173+
bytes = data.getBytes(DEFAULT_CHARSET);
174+
}
175+
catch (UnsupportedEncodingException e)
176+
{
174177
// This should never happen. UTF-8 should always be available but we
175178
// have to catch it so pass it on if it fails.
176179
throw new SparkPostException(e);
177180
}
181+
182+
String lenStr = Integer.toString(bytes.length);
178183
conn.setRequestProperty("Content-Length", lenStr);
179184
conn.setRequestProperty("Content-Type", "application/json");
180185

@@ -184,7 +189,7 @@ private void sendData(HttpURLConnection conn, String data) throws SparkPostExcep
184189
// Send data. At this point connection to server may not be established,
185190
// but writing data to it will trigger the connection.
186191
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
187-
wr.write(data.getBytes(DEFAULT_CHARSET));
192+
wr.write(bytes);
188193
wr.flush();
189194
} catch (IOException ex) {
190195
throw new SparkPostException("Error sending request data:" + ex.toString());

0 commit comments

Comments
 (0)