List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.globallogic.push_service_poc.demo.sender.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException//from ww w. ja v a2 s .co m * if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException * if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an // InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } }
From source file:com.google.android.gcm.demo.sender.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException//from w ww . j av a 2 s . c o m * if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException * if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an // InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } }
From source file:com.facebook.Response.java
@SuppressWarnings("resource") static List<Response> fromHttpConnection(HttpURLConnection connection, RequestBatch requests) { InputStream stream = null;/*w w w .j a v a 2 s .c om*/ FileLruCache cache = null; String cacheKey = null; if (requests instanceof CacheableRequestBatch) { CacheableRequestBatch cacheableRequestBatch = (CacheableRequestBatch) requests; cache = getResponseCache(); cacheKey = cacheableRequestBatch.getCacheKeyOverride(); if (Utility.isNullOrEmpty(cacheKey)) { if (requests.size() == 1) { // Default for single requests is to use the URL. cacheKey = requests.get(0).getUrlForSingleRequest(); } else { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_CACHE_TAG, "Not using cache for cacheable request because no key was specified"); } } // Try loading from cache. If that fails, load from the network. if (!cacheableRequestBatch.getForceRoundTrip() && cache != null && !Utility.isNullOrEmpty(cacheKey)) { try { stream = cache.get(cacheKey); if (stream != null) { return createResponsesFromStream(stream, null, requests, true); } } catch (FacebookException exception) { // retry via roundtrip below } catch (JSONException exception) { } catch (IOException exception) { } finally { Utility.closeQuietly(stream); } } } // Load from the network, and cache the result if not an error. try { if (connection.getResponseCode() >= 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); if ((cache != null) && (cacheKey != null) && (stream != null)) { InputStream interceptStream = cache.interceptAndPut(cacheKey, stream); if (interceptStream != null) { stream = interceptStream; } } } return createResponsesFromStream(stream, connection, requests, false); } catch (FacebookException facebookException) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException); return constructErrorResponses(requests, connection, facebookException); } catch (JSONException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } catch (IOException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } catch (SecurityException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } finally { Utility.closeQuietly(stream); } }
From source file:fr.Axeldu18.PterodactylAPI.Methods.POSTMethods.java
public String call(String methodURL, String data) { try {/* w w w .j a va2s. c om*/ URL url = new URL(methodURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); String hmac = main.getPublicKey() + "." + main.hmac(methodURL + data); System.out.println("DEBUG CALL: " + methodURL); System.out.println("DEBUG CALL2: " + methodURL + data); System.out.println("DEBUG CALL3: " + hmac); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Pterodactyl Java-API"); connection.setRequestProperty("Authorization", "Bearer " + hmac.replaceAll("\n", "")); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return main.readResponse(connection.getInputStream()).toString(); } else { return main.readResponse(connection.getErrorStream()).toString(); } } catch (Exception e) { main.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); return null; } }
From source file:io.lqd.sdk.model.LQNetworkRequest.java
public LQNetworkResponse sendRequest(String token) { String response = null;//from w w w . ja va2 s. c o m int responseCode = -1; InputStream err = null; OutputStream out = null; BufferedOutputStream bout = null; BufferedReader boin = null; HttpURLConnection connection = null; try { URL url = new URL(this.getUrl()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(this.getHttpMethod()); connection.setRequestProperty("Authorization", "Token " + token); connection.setRequestProperty("User-Agent", USER_AGENT); connection.setRequestProperty("Accept", "application/vnd.lqd.v1+json"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setDoInput(true); if (this.getJSON() != null) { connection.setDoOutput(true); out = connection.getOutputStream(); bout = new BufferedOutputStream(out); final StringEntity stringEntity = new StringEntity(this.getJSON(), "UTF-8"); stringEntity.writeTo(bout); } responseCode = connection.getResponseCode(); err = connection.getErrorStream(); GZIPInputStream gzip = new GZIPInputStream(connection.getInputStream()); boin = new BufferedReader(new InputStreamReader(gzip, "UTF-8")); response = boin.readLine(); } catch (IOException e) { LQLog.http("Failed due to " + e + " responseCode " + responseCode); LQLog.http("Error " + inputStreamToString(err)); } finally { if (connection != null) connection.disconnect(); try { if (out != null) out.close(); } catch (IOException e) { } try { if (err != null) err.close(); } catch (IOException e) { } try { if (bout != null) bout.close(); } catch (IOException e) { } try { if (boin != null) boin.close(); } catch (IOException e) { } } if ((response != null) || ((responseCode >= 200) && (responseCode < 300))) { LQLog.http("HTTP Success " + response); return new LQNetworkResponse(responseCode, response); } return new LQNetworkResponse(responseCode); }
From source file:com.machinelinking.api.client.APIClient.java
private InputStream sendRequest(String service, String group, Map<String, Object> properties) throws IOException { try {/*from w w w. jav a2s . co m*/ URL url = new URL(service); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(connTimeout); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); properties.put(ParamsValidator.app_id, appId); properties.put(ParamsValidator.app_key, appKey); StringBuilder data = ParamsValidator.getInstance().buildRequest(group, properties); httpURLConnection.addRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(data.toString().getBytes()); dataOutputStream.close(); if (httpURLConnection.getResponseCode() == 200) { return httpURLConnection.getInputStream(); } else { return httpURLConnection.getErrorStream(); } } catch (MalformedURLException e) { throw new IllegalStateException(e); } }
From source file:motojob.gcm.server.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * //from w w w . j a v a 2 s . c o m * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException * if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException * if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an // InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } }
From source file:com.example.austin.test.TextActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_text); Thread thread = new Thread(new Runnable() { @Override/* w w w . jav a 2 s. c o m*/ public void run() { try { Bundle bundle = getIntent().getExtras(); Bitmap photo = (Bitmap) bundle.get("photo"); ByteArrayOutputStream stream1 = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.PNG, 100, stream1); byte[] fileContent = stream1.toByteArray(); String license_code = "59D1D7B4-61FD-49EB-A549-C77E08B7103A"; String user_name = "austincheng16"; String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true"; URL url = new URL(ocrURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64((user_name + ":" + license_code).getBytes()))); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length)); try { OutputStream stream = connection.getOutputStream(); stream.write(fileContent); stream.close(); int httpCode = connection.getResponseCode(); if (httpCode == HttpURLConnection.HTTP_OK) { String jsonResponse = GetResponseToString(connection.getInputStream()); PrintOCRResponse(jsonResponse); } else { String jsonResponse = GetResponseToString(connection.getErrorStream()); JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); Log.i("austin", "Error Message: " + jsonObj.get("ErrorMessage")); } connection.disconnect(); } catch (IOException e) { Log.i("austin", "IOException"); } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); }
From source file:com.server.xmpp.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty./* www . j a v a 2 s . com*/ * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if there was a JSON parsing error * @throws org.json.simple.parser.ParseException */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException, org.json.simple.parser.ParseException, ParseException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); logger.info("SendNoRetry,Response code:" + status); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.info("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.info("IOException reading response"); return null; } logger.finest("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder().messageId(messageId) .canonicalRegistrationId(canonicalRegId).errorCode(error).build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (CustomParserException e) { throw newIoException(responseBody, e); } }
From source file:com.forecast.io.toolbox.NetworkServiceTask.java
@Override protected INetworkResponse doInBackground(INetworkRequest... params) { INetworkRequest request = params[0]; if (request == null || isCancelled()) { return null; }/* ww w.j a va 2s . c o m*/ InputStream input = null; BufferedOutputStream output = null; HttpURLConnection connection = null; INetworkResponse response = null; try { response = (INetworkResponse) request.getResponse().newInstance(); URL url = new URL(request.getUri().toString()); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(SOCKET_TIME_OUT); connection.setConnectTimeout(CONNECTION_TIME_OUT); connection.setRequestMethod(request.getMethod().toString()); connection.setDoInput(true); if (NetworkUtils.Method.POST.equals(request.getMethod())) { String data = request.getPostBody(); if (data != null) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", request.getContentType()); output = new BufferedOutputStream(connection.getOutputStream()); output.write(data.getBytes()); output.flush(); IOUtils.closeQuietly(output); } } int code = connection.getResponseCode(); input = (code != HttpStatus.SC_OK) ? connection.getErrorStream() : connection.getInputStream(); response.onNetworkResponse(new JSONObject(IOUtils.toString(input))); IOUtils.closeQuietly(input); } catch (Exception e) { Log.e(Constants.LOG_TAG, e.toString()); } finally { if (connection != null) { connection.disconnect(); } IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return response; }