List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** */*from w w w . j av a 2s . com*/ * @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//from w w w .ja v a2s. 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./*from w w w.j a va 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 * @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:org.apache.usergrid.android.sdk.UGClient.java
/** * Forms and initiates a raw synchronous http request and processes the response. * * @param httpMethod the HTTP method in the format: * HTTP_METHOD_<method_name> (e.g. HTTP_METHOD_POST) * @param params the URL parameters to append to the request URL * @param data the body of the request * @param segments additional URL path segments to append to the request URL * @return ApiResponse object/* w w w .j a v a 2 s .c o m*/ */ public ApiResponse doHttpRequest(String httpMethod, Map<String, Object> params, Object data, String... segments) { ApiResponse response = null; OutputStream out = null; InputStream in = null; HttpURLConnection conn = null; String urlAsString = path(apiUrl, segments); try { String contentType = "application/json"; if (httpMethod.equals(HTTP_METHOD_POST) && isEmpty(data) && !isEmpty(params)) { data = encodeParams(params); contentType = "application/x-www-form-urlencoded"; } else { urlAsString = addQueryParams(urlAsString, params); } //logTrace("Invoking " + httpMethod + " to '" + urlAsString + "'"); URL url = new URL(urlAsString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(httpMethod); conn.setRequestProperty("Content-Type", contentType); conn.setUseCaches(false); if ((accessToken != null) && (accessToken.length() > 0)) { String authStr = "Bearer " + accessToken; conn.setRequestProperty("Authorization", authStr); } conn.setDoInput(true); if (httpMethod.equals(HTTP_METHOD_POST) || httpMethod.equals(HTTP_METHOD_PUT)) { if (isEmpty(data)) { data = JsonNodeFactory.instance.objectNode(); } String dataAsString = null; if ((data != null) && (!(data instanceof String))) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); dataAsString = objectMapper.writeValueAsString(data); } else { dataAsString = (String) data; } //logTrace("Posting/putting data: '" + dataAsString + "'"); byte[] dataAsBytes = dataAsString.getBytes(); conn.setRequestProperty("Content-Length", Integer.toString(dataAsBytes.length)); conn.setDoOutput(true); out = conn.getOutputStream(); out.write(dataAsBytes); out.flush(); out.close(); out = null; } in = conn.getInputStream(); if (in != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append('\n'); } String responseAsString = sb.toString(); //logTrace("response from server: '" + responseAsString + "'"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); response = (ApiResponse) objectMapper.readValue(responseAsString, ApiResponse.class); response.setRawResponse(responseAsString); response.setUGClient(this); } else { response = null; logTrace("no response body from server"); } //final int responseCode = conn.getResponseCode(); //logTrace("responseCode from server = " + responseCode); } catch (Exception e) { logError("Error " + httpMethod + " to '" + urlAsString + "'"); if (e != null) { e.printStackTrace(); logError(e.getLocalizedMessage()); } response = null; } catch (Throwable t) { logError("Error " + httpMethod + " to '" + urlAsString + "'"); if (t != null) { t.printStackTrace(); logError(t.getLocalizedMessage()); } response = null; } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception ignored) { } } return response; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make get request./*from w w w . j a v a 2 s . com*/ * * @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./*from w ww. j av a 2 s. 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 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 www . j a v a 2 s .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; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make request./*from w w w .j a v 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 makeRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { //MO Callback boolean isMoCallBack = false; JSONObject jsonObject = null; try { jsonObject = new JSONObject(requestStr); } catch (JSONException error) { error.printStackTrace(); } Iterator<String> keys = jsonObject.keys(); if (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("inboundSMSMessageNotification") || key.equals("deliveryInfoNotification")) { isMoCallBack = true; } } try {// check for charge operation. if true append ESB url JSONObject jsonObj = new JSONObject(requestStr); String transactionOperationStatus = jsonObj.getJSONObject("amountTransaction") .getString("transactionOperationStatus"); String status = "Charged"; if (status.equals(transactionOperationStatus)) { url = modifyEndpoint(url, operatorendpoint.getOperator(), messageContext); } } catch (JSONException ignore) { } ICallresponse icallresponse = null; String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // String encodeurl = URLEncoder.encode(url, "UTF-8"); neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); //connection.setRequestProperty("charset", "utf-8"); 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========================================= /*DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestStr); 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.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(); } log.debug( "Mo OR DN CallBack : " + isMoCallBack + " requestStr : " + requestStr + " retStr : " + retStr); messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); /* TODO:This need to consider when publishing request data if (isMoCallBack) { publishResponseData(statusCode, requestStr, messageContext); }else { publishResponseData(statusCode, retStr, messageContext); }*/ } return retStr; }
From source file:com.acc.android.network.operator.base.BaseHttpOperator.java
public Bitmap openRequestForBitmap(String url, RequestMethod requestMethod, Object paramObject) { if (!this.checkNetWork()) { // return this.notNetError; }//w w w . ja va 2s .com HttpURLConnection conn = null; InputStream inputStream = null; Bitmap bitmap = null; try { // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "Begin a request--->>>>>>>>>>"); // } // try { // url = URLEncoder.encode(url, HttpConstant.ENCODE); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } if (requestMethod == requestMethod.GET && paramObject != null) { // try { url = url + "?" + this.encodeUrlParam(paramObject); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // http://192.168.15.204:82/agcom/rest/roadRest/getBestRoad?id=2&xy=56536.156809,13853.484204 // 56364.173164,12955.347386 } // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "url:", url); LogUtil.info(this, "requestMethod:", requestMethod); LogUtil.info(this, "paramObject:", paramObject); // } // url = url.replace(" ", "%20"); conn = (HttpURLConnection) new URL(url).openConnection(); // System.out // .println("this.sessionStr == null" + this.sessionStr == null); // System.out.println(this.sessionStr == null); if (this.sessionStr != null) { conn.setRequestProperty("cookie", sessionStr); } conn.setConnectTimeout(5 * 1000); if (requestMethod == RequestMethod.GET) { // conn.setRequestMethod(method); // if (isMultipart) { // conn.setRequestProperty("Content-Type", // "multipart/form-data;"); // } else { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // } conn.connect(); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setUseCaches(false); // http: // // 192.168.16.16:8089/agcom/rest/system/locateDiscode/231/10// // Content-Type // if (isMultipart) { // conn.setRequestProperty("Content-Type", // "multipart/form-data;"); // } else { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // } // conn.setRequestProperty("Content-Type", // "application/x-www-form-urlencode"); // conn.connect(); if (paramObject != null) { conn.getOutputStream().write(this.encodeUrlParam(paramObject).getBytes("GBK")); } } inputStream = conn.getInputStream(); // in = new BufferedInputStream(uRLConnection // .getInputStream()); bitmap = BitmapFactory.decodeStream(inputStream); // response = read(inputStream); // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "response:", bitmap == null); // } if (this.sessionStr == null) { Map<String, List<String>> cookies = conn.getHeaderFields(); // this.cookieHeader = conn.getg for (String key : cookies.keySet()) { // System.out.println("sdfdsfd:" + key); if (key == null) { continue; } if ("set-cookie".equals(key.toLowerCase())) { List<String> values = cookies.get(key); String sessionStrTemp = ""; for (String value : values) { sessionStrTemp += value; sessionStrTemp += ";"; // conn.addRequestProperty("set-cookie", string); } // loginSessionStrTemp = // loginSessionStrTemp.substring(0, // loginSessionStrTemp.length() - 1); // System.out.println("loginSessionStrTemp:" // + loginSessionStrTemp); this.sessionStr = sessionStrTemp; this.sessionKey = key; // OldHttpUtil.LOGINSESSIONSTR = sessionStrTemp; // BaseHttpManager.sessionStr = loginSessionStrTemp; break; } } // System.out.println("sessionStr:" + sessionStr); } // System.out.println("openUrl:response:" + response); } catch (Exception e) { // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "End a request with exception below---XXXXXXXXXX"); // } e.printStackTrace(); return bitmap; } finally { if (conn != null) { conn.disconnect(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "End a request successfully---VVVVVVVVVV"); // } return bitmap; }