@@ -40,6 +40,7 @@ public class RestConnection {
4040 private static final Base64 BASE64 = new Base64 ();
4141 private static final String DEFAULT_CHARSET = "UTF-8" ;
4242
43+ private static final int SUCCESS_RESPONSE_STATUS_CODE = 200 ;
4344 private static final int UNAUTHORIZED_RESPONSE_STATUS_CODE = 401 ;
4445 private static final int ACCESS_FORBIDDEN_RESPONSE_STATUS_CODE = 403 ;
4546
@@ -221,6 +222,12 @@ private void sendRequest(HttpURLConnection conn, String data, Response response)
221222 String msg = conn .getResponseMessage ();
222223 response .setResponseMessage (msg );
223224
225+ if (code == UNAUTHORIZED_RESPONSE_STATUS_CODE ) {
226+ throw new SparkPostAuthorizationFailedException ();
227+ } else if (code == ACCESS_FORBIDDEN_RESPONSE_STATUS_CODE ) {
228+ throw new SparkPostAccessForbiddenException ();
229+ }
230+
224231 } catch (IOException ex ) {
225232 throw new SparkPostException ("Connection error:" + ex .toString ());
226233 }
@@ -241,8 +248,13 @@ private Response receiveResponse(HttpURLConnection conn, Response response) thro
241248 sb .append (line );
242249 }
243250
244- response .setResponseBody (sb .toString ());
245- response .setRequestId (conn .getHeaderField ("X-SparkPost-Request-Id" ));
251+ if (response .getResponseCode () == SUCCESS_RESPONSE_STATUS_CODE ) {
252+ response .setResponseBody (sb .toString ());
253+ response .setRequestId (conn .getHeaderField ("X-SparkPost-Request-Id" ));
254+ } else {
255+ throw new SparkPostErrorServerResponseException (sb .toString (), response .getResponseCode ());
256+ }
257+
246258 } catch (FileNotFoundException ex ) {
247259 // We get here if the connection was closed:
248260 // There are cases in REST where the server won't return a response
@@ -269,16 +281,10 @@ private Response receiveResponse(HttpURLConnection conn, Response response) thro
269281 logger .error ("Server Response:" + response );
270282 }
271283
272- if (response .getResponseCode () == UNAUTHORIZED_RESPONSE_STATUS_CODE ) {
273- throw new SparkPostAuthorizationFailedException ();
274- } else if (response .getResponseCode () == ACCESS_FORBIDDEN_RESPONSE_STATUS_CODE ) {
275- throw new SparkPostAccessForbiddenException ();
276- } else {
277- throw new SparkPostErrorServerResponseException (
278- "Error reading server response: " + ex .toString () + ": " + sb .toString () + "(" + response .getResponseMessage () + ")" ,
279- response .getResponseCode ()
280- );
281- }
284+ throw new SparkPostErrorServerResponseException (
285+ "Error reading server response: " + ex .toString () + ": " + sb .toString () + "(" + response .getResponseMessage () + ")" ,
286+ response .getResponseCode ()
287+ );
282288 }
283289 return response ;
284290
0 commit comments