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:edu.pdx.its.portal.routelandia.ApiFetcher.java

/**
 * Go get a string response from the given URL.
 *
 * @param stringURL The URL to go and fetch!
 * @return a string containing the returned result of the HTTP request.
 * @throws IOException/*ww w. j  av  a  2s.c o m*/
 */
private String fetchRawResult(String stringURL, APIResultWrapper retVal) throws IOException {
    String data = "";
    InputStream iStream;
    HttpURLConnection urlConnection;

    Log.i(TAG, "Fetching result from " + stringURL);

    try {
        URL url = new URL(stringURL);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Make sure we've got a good response from the API.
        int status = urlConnection.getResponseCode();
        retVal.setHttpStatus(status);

        // Reading data from url
        try {
            iStream = urlConnection.getInputStream();
        } catch (IOException e) {
            // Our API returns 404's, but they're still JSON...
            iStream = urlConnection.getErrorStream();
        }

        // Create bufferedReader from input
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(iStream));

        StringBuilder stringBuilder = new StringBuilder();

        String line;

        //append all line from buffered Reader into string builder
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        //convert the string builder into string and update its for data
        data = stringBuilder.toString();

        //close the buffered reader
        bufferedReader.close();

    } catch (IOException e) {
        Log.e(TAG, callback_tag + ": Error in getting raw HTTP result: " + e.toString());
        retVal.addException(e);
    }

    if (retVal.getHttpStatus() == 200) {
        retVal.setRawResponse(data);
    } else {
        try {
            // Since errors are still JSON we're going to parse it and get the message
            Object json = new JSONTokener(data).nextValue();

            if (json instanceof JSONObject && ((JSONObject) json).has("error")) {
                retVal.addException(new APIException(
                        ((JSONObject) json).getJSONObject("error").getString("message"), retVal));
            } else {
                retVal.addException(new APIException("Server returned a 404 error for " + stringURL, retVal));
            }

            // Since we've got an exception object now, we need to parse it as an object...j
        } catch (JSONException e) {
            retVal.addException(new APIException("Server returned a 404 error for " + stringURL, retVal));
        }
    }
    return data;
}

From source file:com.amazon.alexa.avs.auth.companionapp.OAuth2ClientForPkce.java

JsonObject postRequest(HttpURLConnection connection, String data) throws IOException {
    int responseCode = -1;
    InputStream error = null;//w w  w  .  j a  v a2 s .  c o  m
    InputStream response = null;
    DataOutputStream outputStream = null;
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoOutput(true);

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(data.getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
    outputStream.close();
    responseCode = connection.getResponseCode();

    try {
        response = connection.getInputStream();
        JsonReader reader = Json.createReader(new InputStreamReader(response, StandardCharsets.UTF_8));
        return reader.readObject();

    } catch (IOException ioException) {
        error = connection.getErrorStream();
        if (error != null) {
            LWAException lwaException = new LWAException(IOUtils.toString(error), responseCode);
            throw lwaException;
        } else {
            throw ioException;
        }
    } finally {
        IOUtils.closeQuietly(error);
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}

From source file:se.vgregion.service.barium.BariumRestClientImpl.java

private void readResponseAndThrowBariumException(HttpURLConnection conn, String msg) throws BariumException {
    LOGGER.error(msg);//from w  ww. j  av  a2  s  .com
    if (conn != null) {
        BufferedInputStream bis = null;
        InputStream inputStream = null;
        try {
            inputStream = conn.getErrorStream();
            bis = new BufferedInputStream(inputStream);
            String errorBody = toString(bis);
            throw new BariumException(errorBody);
        } finally {
            Util.closeClosables(bis, inputStream);
        }
    } else {
        throw new BariumException(msg);
    }
}

From source file:com.example.appengine.java8.LaunchDataflowTemplate.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String project = "YOUR_PROJECT_NAME";
    String bucket = "gs://YOUR_BUCKET_NAME";

    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/cloud-platform");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);

    JSONObject jsonObj = null;/*from  www .jav a2s . c  o m*/
    try {
        JSONObject parameters = new JSONObject().put("datastoreReadGqlQuery", "SELECT * FROM Entries")
                .put("datastoreReadProjectId", project).put("textWritePrefix", bucket + "/output/");
        JSONObject environment = new JSONObject().put("tempLocation", bucket + "/tmp/")
                .put("bypassTempDirValidation", false);
        jsonObj = new JSONObject().put("jobName", "template-" + UUID.randomUUID().toString())
                .put("parameters", parameters).put("environment", environment);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    URL url = new URL(String.format("https://dataflow.googleapis.com/v1b3/projects/%s/templates"
            + ":launch?gcs_path=gs://dataflow-templates/latest/Datastore_to_GCS_Text", project));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    jsonObj.write(writer);
    writer.close();

    int respCode = conn.getResponseCode();
    if (respCode == HttpURLConnection.HTTP_OK) {
        response.setContentType("application/json");
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.getWriter().println(line);
        }
        reader.close();

    } else {
        StringWriter w = new StringWriter();
        IOUtils.copy(conn.getErrorStream(), w, "UTF-8");
        response.getWriter().println(w.toString());
    }
}

From source file:com.newrelic.agent.Deployments.java

static int recordDeployment(CommandLine cmd, AgentConfig config)/*  37:    */ throws Exception
/*  38:    */ {/*from w w w  .j ava  2  s.co  m*/
    /*  39: 35 */ String appName = config.getApplicationName();
    /*  40: 36 */ if (cmd.hasOption("appname")) {
        /*  41: 37 */ appName = cmd.getOptionValue("appname");
        /*  42:    */ }
    /*  43: 39 */ if (appName == null) {
        /*  44: 40 */ throw new IllegalArgumentException(
                "A deployment must be associated with an application.  Set app_name in newrelic.yml or specify the application name with the -appname switch.");
        /*  45:    */ }
    /*  46: 43 */ System.out.println("Recording a deployment for application " + appName);
    /*  47:    */
    /*  48: 45 */ String uri = "/deployments.xml";
    /*  49: 46 */ String payload = getDeploymentPayload(appName, cmd);
    /*  50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : "");
    /*  51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri);
    /*  52:    */
    /*  53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}",
            new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) }));
    /*  54:    */
    /*  55:    */
    /*  56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    /*  57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey());
    /*  58:    */
    /*  59: 56 */ conn.setRequestMethod("POST");
    /*  60: 57 */ conn.setConnectTimeout(10000);
    /*  61: 58 */ conn.setReadTimeout(10000);
    /*  62: 59 */ conn.setDoOutput(true);
    /*  63: 60 */ conn.setDoInput(true);
    /*  64:    */
    /*  65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length()));
    /*  66: 63 */ conn.setFixedLengthStreamingMode(payload.length());
    /*  67: 64 */ conn.getOutputStream().write(payload.getBytes());
    /*  68:    */
    /*  69: 66 */ int responseCode = conn.getResponseCode();
    /*  70: 67 */ if (responseCode < 300)
    /*  71:    */ {
        /*  72: 68 */ System.out.println("Deployment successfully recorded");
        /*  73:    */ }
    /*  74: 69 */ else if (responseCode == 401)
    /*  75:    */ {
        /*  76: 70 */ System.out.println(
                "Unable to notify New Relic of the deployment because of an authorization error.  Check your license key.");
        /*  77: 71 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  78:    */ }
    /*  79:    */ else
    /*  80:    */ {
        /*  81: 73 */ System.out.println("Unable to notify New Relic of the deployment");
        /*  82: 74 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  83:    */ }
    /*  84: 76 */ boolean isError = responseCode >= 300;
    /*  85: 77 */ if ((isError) || (config.isDebugEnabled()))
    /*  86:    */ {
        /*  87: 78 */ System.out.println("Response code: " + responseCode);
        /*  88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream();
        /*  89: 81 */ if (inStream != null)
        /*  90:    */ {
            /*  91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream();
            /*  92: 83 */ Streams.copy(inStream, output);
            /*  93:    */
            /*  94: 85 */ PrintStream out = isError ? System.err : System.out;
            /*  95:    */
            /*  96: 87 */ out.println(output);
            /*  97:    */ }
        /*  98:    */ }
    /*  99: 90 */ return responseCode;
    /* 100:    */ }

From source file:be.appfoundry.custom.google.android.gcm.server.Sender.java

private String makeGcmHttpRequest(Map<Object, Object> jsonRequest) throws InvalidRequestException {
    String requestBody = JSONValue.toJSONString(jsonRequest);
    logger.finest("JSON request: " + requestBody);
    HttpURLConnection conn;
    int status;//from w w w  .ja  va  2  s . c o m
    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);
    return responseBody;
}

From source file:com.google.firebase.auth.migration.AuthMigrator.java

private Task<String> exchangeToken(final String legacyToken) {
    if (legacyToken == null) {
        return Tasks.forResult(null);
    }//  w w  w .  j av  a2s .  co  m
    return Tasks.call(Executors.newCachedThreadPool(), new Callable<String>() {
        @Override
        public String call() throws Exception {
            JSONObject postBody = new JSONObject();
            postBody.put("token", legacyToken);
            HttpURLConnection connection = (HttpURLConnection) exchangeEndpoint.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("POST");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            try {
                osw.write(postBody.toString());
                osw.flush();
            } finally {
                osw.close();
            }
            int responseCode = connection.getResponseCode();

            InputStream is;
            if (responseCode >= 400) {
                is = connection.getErrorStream();
            } else {
                is = connection.getInputStream();
            }
            try {
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int numRead = 0;
                while ((numRead = is.read(buffer)) >= 0) {
                    baos.write(buffer, 0, numRead);
                }
                JSONObject resultObject = new JSONObject(new String(baos.toByteArray()));
                if (responseCode != 200) {
                    throw new FirebaseWebRequestException(
                            resultObject.getJSONObject("error").getString("message"), responseCode);
                }
                return resultObject.getString("token");
            } finally {
                is.close();
            }
        }
    });
}

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

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, java.util.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./*w w  w .ja v  a  2 s .c om*/
 * @throws InvalidRequestException if GCM didn't returned a 200 status.
 * @throws java.io.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 (Exception e) {
        throw newIoException(responseBody, e);
    }
}

From source file:com.mycompany.grupo6ti.GenericResource.java

@GET
@Produces("application/json")
@Path("/obtenerOc/{id}")
public String obtenerOc(@PathParam("id") String id)

{

    try {/* www  . j  a va 2s. c o  m*/
        URL url = new URL("http://localhost:83/obtener/" + id);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream is;
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setUseCaches(true);
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        if (conn.getResponseCode() >= 400) {
            is = conn.getErrorStream();
        } else {
            is = conn.getInputStream();
        }
        String result2 = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            result2 += line;
        }
        rd.close();

        return result2;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "error";
}

From source file:at.ac.tuwien.dsg.celar.mela.jCatascopiaClient.JCatascopiaDataSource.java

/**
 *
 * @param agent for which all available metrics will be retrieved.
 * Attention, this does NOT retrieve metric VALUES
 *///  w w w . jav a 2 s .c  o m
private void updateMetricsForJCatascopiaAgent(JCatascopiaAgent agent) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.url + "/agents/" + agent.getId() + "/availableMetrics");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        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();

            //reuse JCatascopia metric obejcts, to avoid creating new objects all the time
            int nrOfMetricsReportedByJCatascopia = metrics.length();
            int nrOfMetricsInAgent = agentMetrics.size();
            int sizeDifference = nrOfMetricsInAgent - nrOfMetricsReportedByJCatascopia;

            //resize agents metrics list
            if (sizeDifference < 0) {
                //inchrease agents pool
                for (int i = sizeDifference; i < 0; i++) {
                    agentMetrics.add(new JCatascopiaMetric());
                }
            } else if (sizeDifference > 0) {
                for (int i = sizeDifference; i > 0; i--) {
                    agentMetrics.remove(0);
                }
            }

            //populate the metrics pool
            for (int i = 0; i < metrics.length(); i++) {
                JSONObject metric = metrics.getJSONObject(i);
                JCatascopiaMetric jCatascopiaMetric = agentMetrics.get(i);

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

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

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

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

                //get agent group
                if (metric.has("group")) {
                    jCatascopiaMetric.setGroup(metric.getString("group"));
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "JCatascopia group not found in {0}", 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();
        }
    }
}