List of usage examples for java.net HttpURLConnection getURL
public URL getURL()
From source file:com.truebanana.http.HTTPRequest.java
/** * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}. * * @return This {@link HTTPRequest}//from w w w. j a v a 2 s .c o m */ public HTTPRequest executeAsync() { Async.executeAsync(new Runnable() { @Override public void run() { HttpURLConnection urlConnection = buildURLConnection(); // Get request body now if there's a provider if (bodyProvider != null) { body = bodyProvider.getRequestBody(); } // Update socket factory as needed if (urlConnection instanceof HttpsURLConnection) { HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection; try { httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore, trustStorePassword, keyStore, keyStorePassword, !verifySSL)); } catch (GeneralSecurityException e) { e.printStackTrace(); onRequestError(HTTPRequestError.SECURITY_EXCEPTION); onRequestTerminated(); return; // Terminate now } catch (IOException e) { e.printStackTrace(); onRequestError(HTTPRequestError.KEYSTORE_INVALID); onRequestTerminated(); return; // Terminate now } if (!verifySSL) { httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier()); log("SSL Verification Disabled", "**********"); } } log("Endpoint", urlConnection.getURL().toString()); Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> pair = (Map.Entry) iterator.next(); urlConnection.addRequestProperty(pair.getKey(), pair.getValue()); log("Request Header", pair.getKey() + ": " + pair.getValue()); } if (multiPartContent != null) { log("Multipart Request Boundary", multiPartContent.getBoundary()); int counter = 1; for (MultiPartContent.Part part : multiPartContent.getParts()) { log("Request Body Part " + counter, "Name: " + part.getName() + "; File Name: " + part.getFileName()); Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pair = (Map.Entry) it.next(); log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue()); } } } else { log("Request Body", body); } if (mockResponse == null) { // Trigger pre-execute since preparations are complete onPreExecute(); // Write our request body try { if (multiPartContent != null) { multiPartContent.write(urlConnection.getOutputStream()); } else if (body != null) { OutputStream os = urlConnection.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(os); writer.write(body); writer.flush(); writer.close(); os.close(); } } catch (IOException e) { e.printStackTrace(); onRequestError(HTTPRequestError.OTHER); onRequestTerminated(); return; // Terminate now } // Get the response InputStream content; try { content = urlConnection.getInputStream(); onPostExecute(); } catch (SocketTimeoutException e) { // Timeout e.printStackTrace(); onPostExecute(); onRequestError(HTTPRequestError.TIMEOUT); onRequestTerminated(); return; // Terminate now } catch (IOException e) { // All other exceptions e.printStackTrace(); content = urlConnection.getErrorStream(); onPostExecute(); } // Pre-process the response final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content); if (response.isConnectionError()) { onRequestError(HTTPRequestError.OTHER); onRequestTerminated(); return; // Terminate now } // Log response log("Response Message", response.getResponseMessage()); log("Response Content", response.getStringContent()); // Trigger request completed and return the response onRequestCompleted(response); // Terminate the connection urlConnection.disconnect(); onRequestTerminated(); } else { onPreExecute(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } onPostExecute(); log("Response Message", mockResponse.getResponseMessage()); log("Response Content", mockResponse.getStringContent()); onRequestCompleted(mockResponse); urlConnection.disconnect(); onRequestTerminated(); } } }); return this; }
From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java
@Override public String addApiFromDefinition(HttpURLConnection urlConn) throws APIManagementException { try {//from w w w . j av a 2s. c o m urlConn.setDoOutput(true); urlConn.setRequestMethod(APIMgtConstants.HTTP_GET); urlConn.connect(); int responseCode = urlConn.getResponseCode(); if (responseCode == 200) { return addApiFromDefinition(urlConn.getInputStream()); } else { throw new APIManagementException( "Error while getting swagger resource from url : " + urlConn.getURL(), ExceptionCodes.API_DEFINITION_MALFORMED); } } catch (ProtocolException e) { String msg = "Protocol exception while getting the swagger resource from url"; log.error(msg, e); throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED); } catch (IOException e) { String msg = "Error while getting the swagger resource from url"; log.error(msg, e); throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED); } }
From source file:com.google.ytd.SubmitActivity.java
private String uploadMetaData(String filePath, boolean retry) throws IOException { String uploadUrl = INITIAL_UPLOAD_URL; HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true);/*from ww w . j a va 2s . c o m*/ urlConnection.setRequestProperty("Content-Type", "application/atom+xml"); urlConnection.setRequestProperty("Slug", filePath); String atomData; String title = getTitleText(); String description = getDescriptionText(); String category = DEFAULT_VIDEO_CATEGORY; this.tags = DEFAULT_VIDEO_TAGS; if (!Util.isNullOrEmpty(this.getTagsText())) { this.tags = this.getTagsText(); } if (this.videoLocation == null) { String template = Util.readFile(this, R.raw.gdata).toString(); atomData = String.format(template, title, description, category, this.tags); } else { String template = Util.readFile(this, R.raw.gdata_geo).toString(); atomData = String.format(template, title, description, category, this.tags, videoLocation.getLatitude(), videoLocation.getLongitude()); } OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); outStreamWriter.write(atomData); outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); if (responseCode < 200 || responseCode >= 300) { // The response code is 40X if ((responseCode + "").startsWith("4") && retry) { Log.d(LOG_TAG, "retrying to fetch auth token for " + youTubeName); this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken); // Try again with fresh token return uploadMetaData(filePath, false); } else { throw new IOException(String.format("response code='%s' (code %d)" + " for %s", urlConnection.getResponseMessage(), responseCode, urlConnection.getURL())); } } return urlConnection.getHeaderField("Location"); }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** */*from www. java2s .c o m*/ * @param url * @param requestStr * @param messageContext * @return */ public String makeCreditRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); //Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.debug("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL()); log.debug("Southbound Request Headers: " + connection.getRequestProperties()); log.debug("Southbound Request Body: " + requestStr); //UNICODE BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.debug("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage()); log.debug("Southbound Response Headers: " + connection.getHeaderFields()); log.debug("Southbound Response Body: " + retStr); } catch (Exception e) { log.error("[CreditRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); publishWalletPaymentData(statusCode, retStr, messageContext); } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * * @param url/*ww w. j a va 2 s . c om*/ * @param requestStr * @param messageContext * @return */ public String makeWalletRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); //Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); //========================UNICODE PATCH========================================= BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); //========================UNICODE PATCH========================================= statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); publishWalletPaymentData(statusCode, retStr, messageContext); } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make north bound request.//www. ja v a 2s . c o m * * @param operatorendpoint * the operatorendpoint * @param url * the url * @param requestStr * the request str * @param auth * the auth * @param messageContext * the message context * @param inclueHeaders * the inclue headers * @return the int */ public int makeNorthBoundRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { ICallresponse icallresponse = null; String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");// ADDED if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); // Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids // a // ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.info("Northbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Northbound Request Headers: " + connection.getRequestProperties()); } log.info("Northbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); // ========================UNICODE // PATCH========================================= BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); // ========================UNICODE // PATCH========================================= statusCode = connection.getResponseCode(); log.info("Northbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Northbound Response Headers: " + connection.getHeaderFields()); } log.info("Northbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); if (statusCode != 200) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return 0; } finally { if (connection != null) { connection.disconnect(); } } return statusCode; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make get request./*from ww w .j av a 2s. co m*/ * * @param operatorendpoint * the operatorendpoint * @param url * the url * @param requestStr * the request str * @param auth * the auth * @param messageContext * the message context * @return the string */ public String makeGetRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { int statusCode = 0; String retStr = ""; URL neturl; HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // DefaultHttpClient httpClient = new DefaultHttpClient(); String encurl = (requestStr != null) ? url + requestStr : url; neturl = new URL(encurl); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); // Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a // ConcurrentModificationException } } } connection.setUseCaches(false); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make delete request./* w ww. jav a 2 s . c o m*/ * * @param operatorendpoint * the operatorendpoint * @param url * the url * @param requestStr * the request str * @param auth * the auth * @param messageContext * the message context * @return the string */ public String makeDeleteRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { int statusCode = 0; String retStr = ""; URL neturl; HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // DefaultHttpClient httpClient = new DefaultHttpClient(); String encurl = (requestStr != null) ? url + requestStr : url; neturl = new URL(encurl); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("DELETE"); connection.setRequestProperty("Content-Type", "application/json"); if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); // Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a // ConcurrentModificationException } } } connection.setUseCaches(false); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); if (requestStr != null) { connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestStr); wr.flush(); wr.close(); } statusCode = connection.getResponseCode(); log.info("response code: " + statusCode); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401) && (statusCode != 204)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201) || (statusCode == 204)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
public String makeRetrieveSMSGetRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { Gson gson = new GsonBuilder().serializeNulls().create(); int statusCode = 0; String retStr = ""; URL neturl;//from w ww. j av a 2s . c o m HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // DefaultHttpClient httpClient = new DefaultHttpClient(); String encurl = (requestStr != null) ? url + requestStr : url; neturl = new URL(encurl); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); // Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a // ConcurrentModificationException } } } connection.setUseCaches(false); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); SouthboundRetrieveResponse sbRetrieveResponse = gson.fromJson(retStr, SouthboundRetrieveResponse.class); if (sbRetrieveResponse != null && sbRetrieveResponse.getInboundSMSMessageList() != null) { if (sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage() != null && sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage().length != 0) { InboundSMSMessage[] inboundSMSMessageResponses = sbRetrieveResponse.getInboundSMSMessageList() .getInboundSMSMessage(); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(inboundSMSMessageResponses.length)); } else { InboundSMSMessage[] inboundSMSMessageResponses = new InboundSMSMessage[0]; InboundSMSMessageList inboundSMSMessageList = new InboundSMSMessageList(); inboundSMSMessageList.setInboundSMSMessage(inboundSMSMessageResponses); inboundSMSMessageList.setNumberOfMessagesInThisBatch("0"); inboundSMSMessageList.setResourceURL("Not Available"); inboundSMSMessageList.setTotalNumberOfPendingMessages("0"); sbRetrieveResponse.setInboundSMSMessageList(inboundSMSMessageList); InboundSMSMessage[] inboundSMSMessageResponsesN = sbRetrieveResponse.getInboundSMSMessageList() .getInboundSMSMessage(); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(inboundSMSMessageResponsesN.length)); } } else { messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(0)); } } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(0)); return null; } finally { if (connection != null) { connection.disconnect(); } } return retStr; }