use of com.globalcollect.gateway.sdk.client.android.sdk.exception.CommunicationException in project connect-sdk-client-android by Ingenico-ePayments.
the class C2sCommunicator method doHTTPPostRequest.
/**
* Does a POST request with HttpClient
*
* @param location, url where the request is sent to
* @param clientSessionId, used for identification on the GC gateway
* @param metadata, map filled with metadata, which is added to the request
* @param postBody, the content of the postbody
*
* @return HttpURLConnection, which contains the response of the request
*
* @throws CommunicationException
*/
private HttpURLConnection doHTTPPostRequest(String location, String clientSessionId, Map<String, String> metadata, String postBody) throws CommunicationException {
// Initialize the connection
OutputStreamWriter writer = null;
try {
URL url = new URL(location);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set request method to POST
connection.setRequestMethod("POST");
// Add json header
connection.addRequestProperty("Content-Type", "application/json");
// Add sessionId header
if (clientSessionId != null) {
connection.addRequestProperty(HTTP_HEADER_SESSION_ID, "GCS v1Client:" + clientSessionId);
}
// Add metadata header
if (metadata != null) {
connection.addRequestProperty(HTTP_HEADER_METADATA, GcUtil.getBase64EncodedMetadata(metadata));
}
// Log the request
if (Constants.ENABLE_REQUEST_LOGGING) {
logRequest(connection, postBody);
}
// Add post body
connection.setDoOutput(true);
writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(postBody);
writer.flush();
// Check if the response code is HTTP_OK
if (connection.getResponseCode() != 200) {
throw new CommunicationException("No status 200 received, status is :" + connection.getResponseCode());
}
return connection;
} catch (MalformedURLException e) {
Log.e(TAG, "doHTTPPostRequest, Unable to parse url " + location);
throw new CommunicationException("Unable to parse url " + location);
} catch (IOException e) {
Log.e(TAG, "doHTTPPostRequest, IOException while opening connection " + e.getMessage());
throw new CommunicationException("IOException while opening connection " + e.getMessage(), e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
Log.i(TAG, "doHTTPPostRequest, IOException while closing connection " + e.getMessage());
}
}
}
}
Aggregations