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:at.ac.tuwien.dsg.celar.mela.jCatascopiaClient.JCatascopiaDataSource.java

/**
 * Acts directly on the supplied agent and populates its metric list with
 * values// ww w. ja  v  a2  s. c o m
 *
 * @param agent the agent for which the latest metric values will be
 * retrieved
 */
private void getLatestMetricsValuesForJCatascopiaAgent(JCatascopiaAgent agent) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.url + "/metrics");
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Accept", "application/json");

        //write message body
        OutputStream os = connection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os));
        String getMetricsInfoQuerry = "metrics=";
        for (JCatascopiaMetric metric : agent.getAgentMetrics()) {
            getMetricsInfoQuerry += metric.getId() + ",";
        }

        //cut the last ","
        getMetricsInfoQuerry = getMetricsInfoQuerry.substring(0, getMetricsInfoQuerry.lastIndexOf(","));

        bufferedWriter.write(getMetricsInfoQuerry);
        bufferedWriter.flush();
        os.flush();
        os.close();

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
            String line;
            while ((line = reader.readLine()) != null) {
                Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, line);
            }
        }

        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String availableMetrics = "";

        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            availableMetrics += line;
        }

        JSONObject object = new JSONObject(availableMetrics);
        if (object.has("metrics")) {
            JSONArray metrics = object.getJSONArray("metrics");
            List<JCatascopiaMetric> agentMetrics = agent.getAgentMetrics();

            //map of metric indexed on IDs to find easier the metrics (avoids for in for)
            Map<String, JCatascopiaMetric> metricsMap = new HashMap<String, JCatascopiaMetric>(0);
            for (JCatascopiaMetric jCatascopiaMetric : agentMetrics) {
                metricsMap.put(jCatascopiaMetric.getId(), jCatascopiaMetric);
            }

            //populate the metrics pool
            for (int i = 0; i < metrics.length(); i++) {
                JSONObject metric = metrics.getJSONObject(i);
                String metricId = null;
                String metricValue = null;

                //get agent metricID
                if (metric.has("metricID")) {
                    metricId = metric.getString("metricID");
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "JCatascopia metricID not found in {0}", availableMetrics);
                }

                //get metric value
                if (metric.has("value")) {
                    metricValue = metric.getString("value");
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "JCatascopia name not found in {0}", availableMetrics);
                }

                if (metricId == null || metricValue == null) {
                    continue;
                }

                if (metricsMap.containsKey(metricId)) {
                    JCatascopiaMetric jCatascopiaMetric = metricsMap.get(metricId);
                    jCatascopiaMetric.setValue(metricValue);
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "Unrecognized metricId {0} found in {1}",
                            new Object[] { metricId, availableMetrics });
                }

            }

        } else {
            Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                    "No JCatascopia metrics found in {0}", availableMetrics);
        }

    } catch (Exception e) {
        Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Populates the response member.  Closes the connection.
 *///from   w w  w  .  j av a 2  s  .  c  o m
private void readInput(HttpURLConnection connection) throws IOException {
    InputStream is = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[2048];
        try {
            is = connection.getInputStream();
            while (maxBytes == -1 || baos.size() < maxBytes) {
                int bytesRead = is.read(buffer);
                if (bytesRead == -1)
                    break;
                baos.write(buffer, 0, bytesRead);
            }
            response = baos.toByteArray();
            if (followHtmlHeadMetaRefresh && getResponse().indexOf("http-equiv") > 0) {
                try {
                    redirect = parseResponseForHtmlMetaEquiv(getResponse());
                    if (redirect != null)
                        response = new HttpHelper(this, redirect).getBytes();
                } catch (Exception ex) {
                    throw new IllegalArgumentException("Unparseable response: " + ex.getMessage(), ex);
                }

            }
        } catch (IOException ex) {
            InputStream eis = null;
            try {
                eis = connection.getErrorStream();
                while (maxBytes == -1 || baos.size() < maxBytes) {
                    int bytesRead = eis.read(buffer);
                    if (bytesRead == -1)
                        break;
                    baos.write(buffer, 0, bytesRead);
                }
                response = baos.toByteArray();
            } catch (Exception ex2) {
                // throw original exception
            } finally {
                if (eis != null) {
                    eis.close();
                }
            }
            throw ex;
        }
    } finally {
        if (is != null)
            is.close();
        connection.disconnect();
        responseCode = connection.getResponseCode();
        responseMessage = connection.getResponseMessage();
        headers = new HashMap<String, String>();
        for (String headerKey : connection.getHeaderFields().keySet()) {
            if (headerKey == null)
                headers.put("HTTP", connection.getHeaderField(headerKey));
            else
                headers.put(headerKey, connection.getHeaderField(headerKey));
        }
    }
}

From source file:net.sbbi.upnp.messages.ActionMessage.java

/**
 * Executes the message and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a response object containing the UPNP parsed response
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *//*from  www  .  j  av a2 s. c  om*/
public ActionResponse service() throws IOException, UPNPResponseException {
    ActionResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType())
            .append("\">");

    if (serviceAction.getInputActionArguments() != null) {
        // this action requires params so we just set them...
        for (Iterator itr = inputParameters.iterator(); itr.hasNext();) {
            InputParamContainer container = (InputParamContainer) itr.next();
            body.append("<").append(container.name).append(">").append(container.value);
            body.append("</").append(container.name).append(">");
        }
    }
    body.append("</u:").append(serviceAction.getName()).append(">");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    conn.setRequestProperty("SOAPACTION",
            "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\"");
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    out.close();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getActionResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:com.codepine.api.testrail.Request.java

/**
 * Execute this request.//  w  w w  . j  av a2s. c  o  m
 *
 * @return response from TestRail
 */
public T execute() {
    try {

        String url = getUrl();
        HttpURLConnection con = (HttpURLConnection) urlConnectionFactory.getUrlConnection(url);
        con.setRequestMethod(method.name());
        if (config.getApplicationName().isPresent()) {
            con.setRequestProperty("User-Agent", config.getApplicationName().get());
        }
        con.setRequestProperty("Content-Type", "application/json");
        String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(
                (config.getUsername() + ":" + config.getPassword()).getBytes(Charset.forName("UTF-8")));
        con.setRequestProperty("Authorization", basicAuth);
        if (method == Method.POST) {
            Object content = getContent();
            if (content != null) {
                con.setDoOutput(true);
                try (OutputStream outputStream = new BufferedOutputStream(con.getOutputStream())) {
                    JSON.writerWithView(this.getClass()).writeValue(outputStream, content);
                }
            }
        }
        log.debug("Sending " + method + " request to URL : " + url);
        int responseCode = 0;
        try {
            responseCode = con.getResponseCode();
        } catch (IOException e) {
            // swallow it since for 401 getResponseCode throws an IOException
            responseCode = con.getResponseCode();
        }
        log.debug("Response Code : " + responseCode);

        if (responseCode != HttpURLConnection.HTTP_OK) {
            try (InputStream errorStream = con.getErrorStream()) {
                TestRailException.Builder exceptionBuilder = new TestRailException.Builder()
                        .setResponseCode(responseCode);
                if (errorStream == null) {
                    throw exceptionBuilder.setError("<server did not send any error message>").build();
                }
                throw JSON.readerForUpdating(exceptionBuilder).<TestRailException.Builder>readValue(
                        new BufferedInputStream(errorStream)).build();
            }
        }

        try (InputStream responseStream = new BufferedInputStream(con.getInputStream())) {
            Object supplementForDeserialization = getSupplementForDeserialization();
            if (responseClass != null) {
                if (responseClass == Void.class) {
                    return null;
                }
                if (supplementForDeserialization != null) {
                    return JSON
                            .reader(responseClass).with(new InjectableValues.Std()
                                    .addValue(responseClass.toString(), supplementForDeserialization))
                            .readValue(responseStream);
                }
                return JSON.readValue(responseStream, responseClass);
            } else {
                if (supplementForDeserialization != null) {
                    String supplementKey = responseType.getType().toString();
                    if (responseType.getType() instanceof ParameterizedType) {
                        Type[] actualTypes = ((ParameterizedType) responseType.getType())
                                .getActualTypeArguments();
                        if (actualTypes.length == 1 && actualTypes[0] instanceof Class<?>) {
                            supplementKey = actualTypes[0].toString();
                        }
                    }
                    return JSON.reader(responseType).with(
                            new InjectableValues.Std().addValue(supplementKey, supplementForDeserialization))
                            .readValue(responseStream);
                }
                return JSON.readValue(responseStream, responseType);
            }
        }

    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.framework.testcase.testrail.APIClient.java

private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method.equalsIgnoreCase("POST")) {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);/* w ww .j a v  a2 s . c om*/
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = 0;
    try {
        status = conn.getResponseCode();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        System.err.println("the request is timeout from the server ,we quite the test");

    } catch (SSLHandshakeException ex) {
        ex.printStackTrace();
        System.err.println("the request is  Remote host closed connection during handshake");
    }

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {

            new Exception("TestRail API return HTTP " + status + " (No additional error message received)");

        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        new Exception("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}

From source file:TaxSvc.TaxSvc.java

public CancelTaxResult CancelTax(CancelTaxRequest req) {

    //Create URL//  www.j  a  v a 2 s. c o  m
    String taxget = svcURL + "/1.0/tax/cancel";
    URL url;
    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);         //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode.
        { //If we got a more serious error, print out the error message.
            CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response
            return res;
        } else {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response
            return res.CancelTaxResult;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:de.kasoki.jfeedly.helper.HTTPConnections.java

private String sendRequest(String apiUrl, String parameters, boolean isAuthenticated, RequestType type,
        String contentType) {//from w  w w. j  a  va2 s. c om
    try {
        String url = this.jfeedlyHandler.getBaseUrl() + apiUrl.replaceAll(" ", "%20");
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestProperty("User-Agent", "jfeedly");

        if (!contentType.isEmpty()) {
            con.setRequestProperty("Content-Type", contentType);
        }

        if (isAuthenticated) {
            con.setRequestProperty("Authorization",
                    "OAuth " + this.jfeedlyHandler.getConnection().getAccessToken());
        }

        // Send request header
        if (type == RequestType.POST) {
            con.setRequestMethod("POST");

            con.setDoOutput(true);

            DataOutputStream writer = new DataOutputStream(con.getOutputStream());

            writer.write(parameters.getBytes());
            writer.flush();

            writer.close();
        } else if (type == RequestType.GET) {
            con.setRequestMethod("GET");
        } else if (type == RequestType.DELETE) {
            con.setRequestMethod("DELETE");
        } else {
            System.err.println("jfeedly: Unkown RequestType " + type);
        }

        int responseCode = con.getResponseCode();

        if (jfeedlyHandler.getVerbose()) {
            System.out.println("\n" + type + " to: " + url);
            System.out.println("content : " + parameters);
            System.out.println("\nResponse Code : " + responseCode);
        }

        BufferedReader in = null;

        // if error occurred
        if (responseCode >= 400) {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();

        String serverResponse = response.toString();

        if (jfeedlyHandler.getVerbose()) {
            //print response
            String printableResponse = format(serverResponse);

            if (responseCode >= 400) {
                System.err.println(printableResponse);
            } else {
                System.out.println(printableResponse);
            }
        }

        return serverResponse;
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:com.data.pack.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //from   w ww .j  a  v  a 2s  .c o  m
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Util.logd("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.auto.solution.TestManager.TESTRAILTestManager.java

private Object sendRequest(String method, String uri, Object data)
        throws MalformedURLException, IOException, APIException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method == "POST") {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);//from ww w  . ja  v a  2s . co  m
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = conn.getResponseCode();

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {
            throw new APIException(
                    "TestRail API return HTTP " + status + " (No additional error message received)");
        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        throw new APIException("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}

From source file:com.castlemock.web.mock.rest.web.rest.controller.AbstractRestServiceController.java

/**
 * The method provides the functionality to forward a request to another endpoint
 * @param restRequest The incoming request
 * @param restMethod The REST method which the incoming request belongs to
 * @return The response received from the external endpoint
 */// w  ww. j  ava 2  s.  co  m
protected RestResponseDto forwardRequest(final RestRequestDto restRequest, final String projectId,
        final String applicationId, final String resourceId, final RestMethodDto restMethod) {
    if (demoMode) {
        // If the application is configured to run in demo mode, then use mocked response instead
        return mockResponse(restRequest, projectId, applicationId, resourceId, restMethod);
    }

    final RestResponseDto response = new RestResponseDto();
    HttpURLConnection connection = null;
    OutputStream outputStream = null;
    BufferedReader bufferedReader = null;
    try {
        final String parameterUri = HttpMessageSupport.buildParameterUri(restRequest.getHttpParameters());
        final URL url = new URL(restMethod.getForwardedEndpoint() + restRequest.getUri() + parameterUri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(restRequest.getHttpMethod().name());
        for (HttpHeaderDto httpHeader : restRequest.getHttpHeaders()) {
            connection.addRequestProperty(httpHeader.getName(), httpHeader.getValue());
        }

        if (HttpMethod.POST.equals(restRequest.getHttpMethod())
                || HttpMethod.PUT.equals(restRequest.getHttpMethod())
                || HttpMethod.DELETE.equals(restRequest.getHttpMethod())) {
            outputStream = connection.getOutputStream();
            outputStream.write(restRequest.getBody().getBytes());
            outputStream.flush();
        }

        InputStreamReader inputStreamReader = null;
        if (connection.getResponseCode() == OK_RESPONSE) {
            inputStreamReader = new InputStreamReader(connection.getInputStream());
        } else {
            inputStreamReader = new InputStreamReader(connection.getErrorStream());
        }

        bufferedReader = new BufferedReader(inputStreamReader);

        final StringBuilder stringBuilder = new StringBuilder();
        String buffer;
        while ((buffer = bufferedReader.readLine()) != null) {
            stringBuilder.append(buffer);
            stringBuilder.append(NEW_LINE);
        }

        final List<HttpHeaderDto> responseHttpHeaders = HttpMessageSupport.extractHttpHeaders(connection);
        response.setBody(stringBuilder.toString());
        response.setMockResponseName(FORWARDED_RESPONSE_NAME);
        response.setHttpHeaders(responseHttpHeaders);
        response.setHttpStatusCode(connection.getResponseCode());
        return response;
    } catch (IOException exception) {
        LOGGER.error("Unable to forward request", exception);
        throw new RestException("Unable to forward request to configured endpoint");
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException exception) {
                LOGGER.error("Unable to close output stream", exception);
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException exception) {
                LOGGER.error("Unable to close buffered reader", exception);
            }
        }
    }
}