Example usage for java.net HttpURLConnection getRequestMethod

List of usage examples for java.net HttpURLConnection getRequestMethod

Introduction

In this page you can find the example usage for java.net HttpURLConnection getRequestMethod.

Prototype

public String getRequestMethod() 

Source Link

Document

Get the request method.

Usage

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 * Make north bound request.// w w w. ja  va 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
 * @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 w w  w  . j a  va2 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 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  w  w .jav  a 2 s  .c om
 *
 * @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  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;
}

From source file:groovyx.net.http.HttpURLClient.java

/**
 * Perform a request.  Parameters are:/*ww w. j  av a2s  . c  om*/
 * <dl>
 *   <dt>url</dt><dd>the entire request URL</dd>
 *   <dt>path</dt><dd>the path portion of the request URL, if a default
 *     URL is set on this instance.</dd>
 *   <dt>query</dt><dd>URL query parameters for this request.</dd>
 *   <dt>timeout</dt><dd>see {@link HttpURLConnection#setReadTimeout(int)}</dd>
 *   <dt>method</dt><dd>This defaults to GET, or POST if a <code>body</code>
 *   parameter is also specified.</dd>
 *   <dt>contentType</dt><dd>Explicitly specify how to parse the response.
 *     If this value is ContentType.ANY, the response <code>Content-Type</code>
 *     header is used to determine how to parse the response.</dd>
 *   <dt>requestContentType</dt><dd>used in a PUT or POST request to
 *     transform the request body and set the proper
 *     <code>Content-Type</code> header.  This defaults to the
 *     <code>contentType</code> if unset.</dd>
 *   <dt>auth</dt><dd>Basic authorization; pass the value as a list in the
 *   form [user, pass]</dd>
 *   <dt>headers</dt><dd>additional request headers, as a map</dd>
 *   <dt>body</dt><dd>request content body, for a PUT or POST request.
 *     This will be encoded using the requestContentType</dd>
 * </dl>
 * @param args named parameters
 * @return the parsed response
 * @throws URISyntaxException
 * @throws MalformedURLException
 * @throws IOException
 */
public HttpResponseDecorator request(Map<String, ?> args)
        throws URISyntaxException, MalformedURLException, IOException {

    // copy so we don't modify the original collection when removing items:
    args = new HashMap<String, Object>(args);

    Object arg = args.remove("url");
    if (arg == null && this.defaultURL == null)
        throw new IllegalStateException("Either the 'defaultURL' property"
                + " must be set or a 'url' parameter must be passed to the " + "request method.");
    URIBuilder url = arg != null ? new URIBuilder(arg.toString()) : defaultURL.clone();

    arg = null;
    arg = args.remove("path");
    if (arg != null)
        url.setPath(arg.toString());
    arg = null;
    arg = args.remove("query");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'query' must be a map");
        url.setQuery((Map<?, ?>) arg);
    }

    HttpURLConnection conn = (HttpURLConnection) url.toURL().openConnection();
    conn.setInstanceFollowRedirects(this.followRedirects);

    arg = null;
    arg = args.remove("timeout");
    if (arg != null)
        conn.setConnectTimeout(Integer.parseInt(arg.toString()));

    arg = null;
    arg = args.remove("method");
    if (arg != null)
        conn.setRequestMethod(arg.toString());

    arg = null;
    arg = args.remove("contentType");
    Object contentType = arg != null ? arg : this.contentType;
    if (contentType instanceof ContentType)
        conn.addRequestProperty("Accept", ((ContentType) contentType).getAcceptHeader());

    arg = null;
    arg = args.remove("requestContentType");
    String requestContentType = arg != null ? arg.toString()
            : this.requestContentType != null ? this.requestContentType.toString()
                    : contentType != null ? contentType.toString() : null;

    // must add default headers before setting auth:
    for (String key : defaultHeaders.keySet())
        conn.addRequestProperty(key, defaultHeaders.get(key));

    arg = null;
    arg = args.remove("auth");
    if (arg != null) {
        if (oauth != null)
            log.warn("You are trying to use both OAuth and basic authentication!");
        try {
            List<?> vals = (List<?>) arg;
            conn.addRequestProperty("Authorization",
                    getBasicAuthHeader(vals.get(0).toString(), vals.get(1).toString()));
        } catch (Exception ex) {
            throw new IllegalArgumentException("Auth argument must be a list in the form [user,pass]");
        }
    }

    arg = null;
    arg = args.remove("headers");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'headers' must be a map");
        Map<?, ?> headers = (Map<?, ?>) arg;
        for (Object key : headers.keySet())
            conn.addRequestProperty(key.toString(), headers.get(key).toString());
    }

    arg = null;
    arg = args.remove("body");
    if (arg != null) { // if there is a request POST or PUT body
        conn.setDoOutput(true);
        final HttpEntity body = (HttpEntity) encoderRegistry.getAt(requestContentType).call(arg);
        // TODO configurable request charset

        //TODO don't override if there is a 'content-type' in the headers list
        conn.addRequestProperty("Content-Type", requestContentType);
        try {
            // OAuth Sign if necessary.
            if (oauth != null)
                conn = oauth.sign(conn, body);
            // send request data
            DefaultGroovyMethods.leftShift(conn.getOutputStream(), body.getContent());
        } finally {
            conn.getOutputStream().close();
        }
    }
    // sign the request if we're using OAuth
    else if (oauth != null)
        conn = oauth.sign(conn, null);

    if (args.size() > 0) {
        String illegalArgs = "";
        for (String k : args.keySet())
            illegalArgs += k + ",";
        throw new IllegalArgumentException("Unknown named parameters: " + illegalArgs);
    }

    String method = conn.getRequestMethod();
    log.debug(method + " " + url);

    HttpResponse response = new HttpURLResponseAdapter(conn);
    if (ContentType.ANY.equals(contentType))
        contentType = conn.getContentType();

    Object result = this.getparsedResult(method, contentType, response);

    log.debug(response.getStatusLine());
    HttpResponseDecorator decoratedResponse = new HttpResponseDecorator(response, result);

    if (log.isTraceEnabled()) {
        for (Header h : decoratedResponse.getHeaders())
            log.trace(" << " + h.getName() + " : " + h.getValue());
    }

    if (conn.getResponseCode() > 399)
        throw new HttpResponseException(decoratedResponse);

    return decoratedResponse;
}

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 * Make request.//from  w  w  w  . j av a  2  s.  c om
 *
 * @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.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc//from w w  w  . j a  v a2 s .c  om
 */
public int getResponseCode(Object connection) throws IOException {
    // workaround for Android bug discussed here: http://stackoverflow.com/questions/17638398/androids-httpurlconnection-throws-eofexception-on-head-requests
    HttpURLConnection con = (HttpURLConnection) connection;
    if ("head".equalsIgnoreCase(con.getRequestMethod())) {
        con.setRequestProperty("Accept-Encoding", "");
    }
    return ((HttpURLConnection) connection).getResponseCode();
}