Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

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

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:org.andstatus.app.net.http.HttpConnectionOAuthJavaNet.java

/**
 * Partially borrowed from the "Impeller" code !
 *///from  w  w  w. j  av a2  s  .  c om
@Override
public void registerClient(String path) throws ConnectionException {
    String logmsg = "registerClient; for " + data.originUrl + "; URL='" + pathToUrlString(path) + "'";
    MyLog.v(this, logmsg);
    String consumerKey = "";
    String consumerSecret = "";
    data.oauthClientKeys.clear();
    Writer writer = null;
    try {
        URL endpoint = new URL(pathToUrlString(path));
        HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection();

        Map<String, String> params = new HashMap<String, String>();
        params.put("type", "client_associate");
        params.put("application_type", "native");
        params.put("redirect_uris", HttpConnection.CALLBACK_URI.toString());
        params.put("client_name", HttpConnection.USER_AGENT);
        params.put("application_name", HttpConnection.USER_AGENT);
        String requestBody = HttpConnectionUtils.encode(params);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        writer = new OutputStreamWriter(conn.getOutputStream(), UTF_8);
        writer.write(requestBody);
        writer.close();

        if (conn.getResponseCode() != 200) {
            String msg = HttpConnectionUtils.readStreamToString(conn.getErrorStream());
            MyLog.i(this, "Server returned an error response: " + msg);
            MyLog.i(this, "Server returned an error response: " + conn.getResponseMessage());
        } else {
            String response = HttpConnectionUtils.readStreamToString(conn.getInputStream());
            JSONObject jso = new JSONObject(response);
            if (jso != null) {
                consumerKey = jso.getString("client_id");
                consumerSecret = jso.getString("client_secret");
                data.oauthClientKeys.setConsumerKeyAndSecret(consumerKey, consumerSecret);
            }
        }
    } catch (IOException e) {
        MyLog.i(this, logmsg, e);
    } catch (JSONException e) {
        MyLog.i(this, logmsg, e);
    } finally {
        DbUtils.closeSilently(writer);
    }
    if (data.oauthClientKeys.areKeysPresent()) {
        MyLog.v(this, "Completed " + logmsg);
    } else {
        throw ConnectionException.fromStatusCodeAndHost(StatusCode.NO_CREDENTIALS_FOR_HOST,
                "No client keys for the host yet; " + logmsg, data.originUrl);
    }
}

From source file:motojob.gcm.server.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, List, int)} for more info.
 * //from  www . j  a  v a2 s  .  c om
 * @return multicast results if the message was sent successfully,
 *         {@literal null} if it failed but could be retried.
 * 
 * @throws IllegalArgumentException
 *             if registrationIds is {@literal null} or empty.
 * @throws InvalidRequestException
 *             if GCM didn't returned a 200 status.
 * @throws IOException
 *             if there was a JSON parsing error
 */
public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException {

    if (nonNull(registrationIds).isEmpty()) {
        throw new IllegalArgumentException("registrationIds cannot be empty");
    }
    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
    setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
    setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());

    jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);

    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }
    String requestBody = JSONValue.toJSONString(jsonRequest);
    logger.finest("JSON request: " + requestBody);
    HttpURLConnection conn;
    int status;
    try {
        conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
        status = conn.getResponseCode();
    } catch (IOException e) {
        logger.log(Level.FINE, "IOException posting to GCM", e);
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            logger.finest("JSON error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an
            // InvalidRequestException
            // anyways
            responseBody = "N/A";
            logger.log(Level.FINE, "Exception reading response: ", e);
        }
        throw new InvalidRequestException(status, responseBody);
    }
    try {
        responseBody = getAndClose(conn.getInputStream());
    } catch (IOException e) {
        logger.log(Level.WARNING, "IOException reading response", e);
        return null;
    }
    logger.finest("JSON response: " + responseBody);
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse;
    try {
        jsonResponse = (JSONObject) parser.parse(responseBody);
        int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
        if (results != null) {
            for (Map<String, Object> jsonResult : results) {
                String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
                String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
                String error = (String) jsonResult.get(JSON_ERROR);
                Result result = new Result.Builder().messageId(messageId)
                        .canonicalRegistrationId(canonicalRegId).errorCode(error).build();
                builder.addResult(result);
            }
        }
        MulticastResult multicastResult = builder.build();
        return multicastResult;
    } catch (ParseException e) {
        throw newIoException(responseBody, e);
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:com.mobile.godot.core.service.task.GodotAction.java

@Override
public void run() {

    System.out.println("inside runnable");

    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

    URL url = GodotURLUtils.parseToURL(this.mServlet, this.mParams);

    System.out.println("url: " + url);

    HttpURLConnection connection = null;
    InputStream iStream;/*from   www . j a v  a 2 s . c o  m*/
    InputStream eStream;
    int responseCode = 0;
    String data = null;

    try {

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        if (!url.getHost().equals(connection.getURL().getHost())) {
            this.mHandler.obtainMessage(GodotMessage.Error.REDIRECTION_ERROR).sendToTarget();
            connection.disconnect();
            return;
        }

        try {

            iStream = new BufferedInputStream(connection.getInputStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } catch (IOException exc) {

            eStream = new BufferedInputStream(connection.getErrorStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(eStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } finally {

            if (data != null) {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode), data).sendToTarget();

            } else {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode)).sendToTarget();

            }
        }

    } catch (IOException exc) {

        this.mHandler.obtainMessage(GodotMessage.Error.SERVER_ERROR).sendToTarget();

    } finally {

        connection.disconnect();

    }

}

From source file:com.motorola.motoask.gcm.server.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, List, int)} for more info.
 *
 * @return multicast results if the message was sent successfully,
 *         {@literal null} if it failed but could be retried.
 *
 * @throws IllegalArgumentException if registrationIds is {@literal null} or
 *         empty./*from w w w.j a  v a  2 s  .  c o  m*/
 * @throws InvalidRequestException if GCM didn't returned a 200 status.
 * @throws IOException if there was a JSON parsing error
 */
public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException {
    logger.info("sendNoRetry()");
    if (nonNull(registrationIds).isEmpty()) {
        throw new IllegalArgumentException("registrationIds cannot be empty");
    }

    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    //setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
    //setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
    setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    //setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
    jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
    Map<String, String> payload = message.getData();

    if (!payload.isEmpty()) {
        logger.info("payload is ok" + payload.toString());
        jsonRequest.put(JSON_PAYLOAD, payload);

    } else {

        logger.info("payload is fucking empty!!");
    }
    String requestBody = JSONValue.toJSONString(jsonRequest);
    logger.info("JSON request: " + requestBody);
    HttpURLConnection conn;
    int status;
    try {
        conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
        status = conn.getResponseCode();
        logger.info("status is " + status);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "IOException posting to GCM", e);
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            logger.info("JSON error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an InvalidRequestException
            // anyways
            responseBody = "N/A";
            logger.log(Level.INFO, "Exception reading response: ", e);
        }
        throw new InvalidRequestException(status, responseBody);
    }
    try {
        responseBody = getAndClose(conn.getInputStream());
    } catch (IOException e) {
        logger.log(Level.WARNING, "IOException reading response", e);
        return null;
    }
    logger.info("JSON response: " + responseBody);
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse;
    try {
        jsonResponse = (JSONObject) parser.parse(responseBody);
        int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
        if (results != null) {
            for (Map<String, Object> jsonResult : results) {
                String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
                String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
                String error = (String) jsonResult.get(JSON_ERROR);
                Result result = new Result.Builder().messageId(messageId)
                        .canonicalRegistrationId(canonicalRegId).errorCode(error).build();
                builder.addResult(result);
            }
        }
        MulticastResult multicastResult = builder.build();
        return multicastResult;
    } catch (ParseException e) {
        throw newIoException(responseBody, e);
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:org.jongo.mocks.JongoClient.java

private JongoResponse doRequest(final String url, final String method, final String jsonParameters) {
    JongoResponse response = null;/* w w w .j  a va  2 s  .c o m*/

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection();
        con.setRequestMethod(method);
        con.setRequestProperty("Accept", MediaType.APPLICATION_XML);
        con.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
        con.setRequestProperty("Content-Length", "" + Integer.toString(jsonParameters.getBytes().length));
        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonParameters);
        wr.flush();
        wr.close();

        //            BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));

        BufferedReader r = null;
        if (con.getResponseCode() != Response.Status.OK.getStatusCode()
                && con.getResponseCode() != Response.Status.CREATED.getStatusCode()) {
            r = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            r = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        StringBuilder rawresponse = new StringBuilder();
        String strLine = null;
        while ((strLine = r.readLine()) != null) {
            rawresponse.append(strLine);
            rawresponse.append("\n");
        }

        try {
            response = XmlXstreamTest.successFromXML(rawresponse.toString());
        } catch (Exception e) {
            response = XmlXstreamTest.errorFromXML(rawresponse.toString());
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return response;
}

From source file:com.weebly.opus1269.copyeverywhere.cloud.HttpRequest.java

/**
 * Post the request/*from  w  w  w  .  j a va  2 s  .c o m*/
 *
 * @param url         where to post to
 * @param requestBody the body of the request
 * @throws IOException
 */
public void doPost(String url, String requestBody) throws IOException {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "HTTP request. body: " + requestBody);
    }

    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes(UTF_8).length);
    conn.setRequestMethod("POST");
    for (int i = 0; i < mHeaders.size(); i++) {
        conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i));
    }
    OutputStream out = null;
    try {
        out = conn.getOutputStream();
        out.write(requestBody.getBytes(UTF_8));
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ignored) {
                // Ignore.
            }
        }
    }

    mResponseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (mResponseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        mResponseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (final IOException ignored) {
                // Ignore.
            }
        }
    }

    if (BuildConfig.DEBUG) {
        Log.i(TAG, "HTTP response. body: " + mResponseBody);
    }

    conn.disconnect();
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

/**
 * Does an HTTP post for a given form data string.
 *
 * @param data is the form data string.//w  ww .j  av  a  2 s .c o m
 * @param url  is the url to post to.
 * @return the return string from the server.
 * @throws java.io.IOException
 */
public static String postData(String data, URL url) throws IOException {

    String result = null;

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try {
        HttpHelpers.addCommonHeaders(conn);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(data);
        writer.flush();
        writer.close();

        String line;
        BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn);
        while ((line = reader.readLine()) != null) {
            if (result == null)
                result = line;
            else
                result += line;
        }

        reader.close();
    } catch (IOException ex) {
        Log.e(TAG, "Failed to read stream data", ex);

        String error = null;

        // TODO Am not yet sure if the section below should make it in the production release.
        // I mainly use it to get details of a failed http request. I get a FileNotFoundException
        // when actually the url is correct but an exception was thrown at the server and i use this
        // to get the server call stack for debugging purposes.
        try {
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            while ((line = reader.readLine()) != null) {
                if (error == null)
                    error = line;
                else
                    error += line;
            }

            reader.close();
        } catch (Exception e) {
            Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex);
        }
    }

    return result;
}

From source file:circleplus.app.http.AbstractHttpApi.java

protected BaseType executeHttpRequest(URL url, int method, JSONObject json, Parser<? extends BaseType> parser)
        throws IOException, Exception {
    InputStream is = null;/*from ww  w  .j  a  va  2s.c o m*/
    OutputStream os = null;
    HttpURLConnection conn = null;
    try {
        if (method == REQUEST_METHOD_POST && json != null) {
            conn = getHttpURLConnection(url, method, true);
            byte[] bytes = json.toString(0).getBytes(UTF8_CHARSET);
            os = conn.getOutputStream();
            os.write(bytes);
            os.flush();
            os.close();
        } else {
            conn = getHttpURLConnection(url, method);
        }

        int response = conn.getResponseCode();
        if (D)
            Log.d(TAG, "Response code = " + response);

        switch (response) {
        case 200:
            is = conn.getInputStream();
            // TODO: calculate length
            String content = readStream(is, 2048 * 4);
            if (D)
                Log.d(TAG, content);
            return JSONUtils.consume(parser, content);

        // BAD REQUEST
        case 400:
            is = conn.getErrorStream();
            String errorContent = readStream(is, 128);
            if (D)
                Log.d(TAG, "Http code: 400. Error message: " + errorContent);
            return JSONUtils.consume(new StatusParser(), errorContent);

        case 404:
            if (D)
                Log.d(TAG, "Http code: 404");
            throw new IOException("Http code: 404");

        case 500:
            if (D)
                Log.d(TAG, "Http code: 500");
            throw new IOException("Http code: 500");

        default:
            if (D)
                Log.d(TAG, "Default case for status code reached: " + response);
            throw new IOException("Http code: " + response);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        if (is != null) {
            is.close();
        }
        if (os != null) {
            os.close();
        }
    }
}

From source file:com.nimbits.server.gcm.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, String, int)} for more info.
 *
 * @return result of the post, or {@literal null} if the GCM service was
 *         unavailable or any network exception caused the request to fail.
 *
 * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
 * @throws IllegalArgumentException if registrationId is {@literal null}.
 *///from  w ww.j a v a 2  s .  c om
public Result sendNoRetry(Message message, String registrationId) throws IOException {
    StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
    Boolean delayWhileIdle = message.isDelayWhileIdle();
    if (delayWhileIdle != null) {
        addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
    }
    Boolean dryRun = message.isDryRun();
    if (dryRun != null) {
        addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
    }
    String collapseKey = message.getCollapseKey();
    if (collapseKey != null) {
        addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
    }
    String restrictedPackageName = message.getRestrictedPackageName();
    if (restrictedPackageName != null) {
        addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
    }
    Integer timeToLive = message.getTimeToLive();
    if (timeToLive != null) {
        addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
    }
    for (Entry<String, String> entry : message.getData().entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (key == null || value == null) {
            logger.warning("Ignoring payload entry thas has null: " + entry);
        } else {
            key = PARAM_PAYLOAD_PREFIX + key;
            addParameter(body, key, URLEncoder.encode(value, UTF8));
        }
    }
    String requestBody = body.toString();
    logger.finest("Request body: " + requestBody);
    HttpURLConnection conn;
    int status;
    try {
        conn = post(GCM_SEND_ENDPOINT, requestBody);
        status = conn.getResponseCode();
    } catch (IOException e) {
        logger.log(Level.FINE, "IOException posting to GCM", e);
        return null;
    }
    if (status / 100 == 5) {
        logger.fine("GCM service is unavailable (status " + status + ")");
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            logger.finest("Plain post error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an InvalidRequestException
            // anyways
            responseBody = "N/A";
            logger.log(Level.FINE, "Exception reading response: ", e);
        }
        throw new InvalidRequestException(status, responseBody);
    } else {
        try {
            responseBody = getAndClose(conn.getInputStream());
        } catch (IOException e) {
            logger.log(Level.WARNING, "Exception reading response: ", e);
            // return null so it can retry
            return null;
        }
    }
    String[] lines = responseBody.split("\n");
    if (lines.length == 0 || lines[0].equals("")) {
        throw new IOException("Received empty response from GCM service.");
    }
    String firstLine = lines[0];
    String[] responseParts = split(firstLine);
    String token = responseParts[0];
    String value = responseParts[1];
    if (token.equals(TOKEN_MESSAGE_ID)) {
        Result.Builder builder = new Result.Builder().messageId(value);
        // check for canonical registration id
        if (lines.length > 1) {
            String secondLine = lines[1];
            responseParts = split(secondLine);
            token = responseParts[0];
            value = responseParts[1];
            if (token.equals(TOKEN_CANONICAL_REG_ID)) {
                builder.canonicalRegistrationId(value);
            } else {
                logger.warning("Invalid response from GCM: " + responseBody);
            }
        }
        Result result = builder.build();
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Message created succesfully (" + result + ")");
        }
        return result;
    } else if (token.equals(TOKEN_ERROR)) {
        return new Result.Builder().errorCode(value).build();
    } else {
        throw new IOException("Invalid response from GCM: " + responseBody);
    }
}

From source file:com.impetus.ankush.common.utils.AnkushRestClient.java

/**
 * Method sendNodeInfo./*from  w  ww  .  java2 s  .  co  m*/
 * 
 * @param urlPath
 *            String
 * @param input
 *            String
 * @return String
 * @throws IOException
 */
public HttpResult sendRequest(String urlPath, String input, String method, String accept, String contentType) {
    HttpURLConnection conn = null;
    String output = "";
    OutputStream os = null;

    // Http Response object.
    HttpResult result = new HttpResult();
    boolean status = true;

    try {
        URL url = new URL(urlPath);
        logger.info("Executing request : " + urlPath);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method);
        conn.setRequestProperty("Accept", accept);
        conn.setRequestProperty("Content-type", contentType);
        if (input != null && !input.isEmpty()) {
            os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
        }
        String buffer = "";
        BufferedReader br;
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            status = false;
            String error = "";
            // get ErrorStream
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));

            while ((buffer = br.readLine()) != null) {
                error += buffer;
            }
            result.setError(error);
        }
        br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        while ((buffer = br.readLine()) != null) {
            output += buffer;
        }
    } catch (Exception e) {
        logger.debug(e.getMessage());
        logger.error("Exception in executing request : " + urlPath, e);
        result.setError(e.getLocalizedMessage());
        status = false;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        if (os != null) {
            IOUtils.closeQuietly(os);
        }
    }
    result.setStatus(status);
    result.setOutput(output);

    return result;
}