Example usage for java.net HttpURLConnection HTTP_OK

List of usage examples for java.net HttpURLConnection HTTP_OK

Introduction

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

Prototype

int HTTP_OK

To view the source code for java.net HttpURLConnection HTTP_OK.

Click Source Link

Document

HTTP Status-Code 200: OK.

Usage

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsEc2MetadataClient.java

private String readResource(String resourcePath) {
    HttpURLConnection connection = null;
    URL url = null;//from w  w w  .j a  v  a2 s .  com
    try {
        url = getEc2MetadataServiceUrlForResource(resourcePath);
        log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(SECOND * 2);
        connection.setReadTimeout(SECOND * 7);
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_OK
                && connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
            return readResponse(connection);
        } else {
            return null;
        }
    } catch (Exception e) {
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

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 )
 *//*  w w  w .  ja v a  2s  . 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.aokyu.dev.pocket.PocketClient.java

public RetrieveResponse retrieve(AccessToken accessToken, RetrieveRequest retrieveRequest)
        throws IOException, InvalidRequestException, PocketException {
    String endpoint = PocketServer.getEndpoint(RequestType.RETRIEVE);
    URL requestUrl = new URL(endpoint);
    HttpHeaders headers = new HttpHeaders();
    headers.put(HttpHeader.CONTENT_TYPE, ContentType.JSON_WITH_UTF8.get());
    headers.put(HttpHeader.X_ACCEPT, ContentType.JSON.get());
    headers.put(HttpHeader.HOST, requestUrl.getHost());

    retrieveRequest.put(AddRequest.Parameter.ACCESS_TOKEN, accessToken.get());
    retrieveRequest.put(AddRequest.Parameter.CONSUMER_KEY, mConsumerKey.get());

    HttpParameters parameters = retrieveRequest.getHttpParameters();

    HttpRequest request = new HttpRequest(HttpMethod.POST, requestUrl, headers, parameters);

    HttpResponse response = null;//from w w w. j a v a  2  s . com
    JSONObject jsonObj = null;
    Map<String, List<String>> responseHeaders = null;
    try {
        response = mClient.execute(request);
        if (response.getStatusCode() == HttpURLConnection.HTTP_OK) {
            jsonObj = response.getResponseAsJSONObject();
            responseHeaders = response.getHeaderFields();
        } else {
            ErrorResponse error = new ErrorResponse(response);
            mErrorHandler.handleResponse(error);
        }
    } catch (JSONException e) {
        throw new PocketException(e.getMessage());
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }

    RetrieveResponse retrieveResponse = null;
    if (jsonObj != null) {
        try {
            retrieveResponse = new RetrieveResponse(jsonObj, responseHeaders);
        } catch (JSONException e) {
            throw new PocketException(e.getMessage());
        }
    }

    return retrieveResponse;
}

From source file:ja.ohac.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//w  w w.  j a  v  a2 s .  c  o  m

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final BigInteger rate = GenericUtils.parseCoin(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, rate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java

@Test
public void testAvroData() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    httpConfigs.appIdViaQueryParamAllowed = true;
    DataParserFormatConfig dataFormatConfig = new DataParserFormatConfig();
    dataFormatConfig.avroSchemaSource = OriginAvroSchemaSource.SOURCE;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.AVRO, dataFormatConfig);
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();/*www.j a va 2s .co  m*/
    try {
        final List<Record> records = new ArrayList<>();
        runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
            @Override
            public void processBatch(StageRunner.Output output) {
                records.clear();
                records.addAll(output.getRecords().get("a"));
            }
        });

        // wait for the HTTP server up and running
        HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server");
        await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

        String url = "http://localhost:" + httpConfigs.getPort() + "?"
                + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
        File avroDataFile = SdcAvroTestUtil.createAvroDataFile();
        InputStream in = new FileInputStream(avroDataFile);
        byte[] avroData = IOUtils.toByteArray(in);
        Response response = ClientBuilder.newClient().target(url).request()
                .post(Entity.entity(avroData, MediaType.APPLICATION_OCTET_STREAM_TYPE));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
        Assert.assertEquals(3, records.size());
        Assert.assertEquals("a", records.get(0).get("/name").getValue());
        Assert.assertEquals("b", records.get(1).get("/name").getValue());
        Assert.assertEquals("c", records.get(2).get("/name").getValue());
        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

From source file:org.eclipse.hono.service.credentials.CredentialsHttpEndpoint.java

/**
 * Gets credentials by auth-id and type.
 * //from  w ww.j  av a2  s . c om
 * @param ctx The context to retrieve the query parameters from.
 */
private void getCredentials(final RoutingContext ctx) {

    // mandatory params
    final String tenantId = getTenantParam(ctx);
    final String authId = getAuthIdParam(ctx);
    final String type = getTypeParam(ctx);

    logger.debug("getCredentials [tenant: {}, auth-id: {}, type: {}]", tenantId, authId, type);

    final JsonObject requestMsg = CredentialsConstants.getServiceGetRequestAsJson(tenantId, null, authId, type);

    sendAction(ctx, requestMsg,
            getDefaultResponseHandler(ctx, status -> status == HttpURLConnection.HTTP_OK, null));

}

From source file:org.jboss.as.test.manualmode.web.valve.authenticator.ValveUtil.java

public static Header[] hitValve(URL url) throws Exception {
    return hitValve(url, HttpURLConnection.HTTP_OK);

}

From source file:org.jboss.pull.player.LabelProcessor.java

private void setLabels(final String issueUrl, final Collection<String> labels) {
    // Build a list of the new labels
    final StringBuilder sb = new StringBuilder(32).append('[');
    final int size = labels.size();
    int counter = 0;
    for (String label : labels) {
        sb.append('"').append(label).append('"');
        if (++counter < size) {
            sb.append(',');
        }/*from   w w  w.java2  s  .com*/
    }
    sb.append(']');
    try {
        final HttpPut put = new HttpPut(issueUrl + "/labels");
        GitHubApi.addDefaultHeaders(put);
        put.setEntity(new StringEntity(sb.toString()));
        execute(put, HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace(err);
    }

}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.java

/**
 * When the servlet container generates a 404 page not found, we want to pass
 * it through without caching and without adding anything to it.
 * <p/>//from   w  w  w .  j  ava 2s .  com
 * Manual Test: wget -d --server-response --header='Accept-Encoding: gzip'  http://localhost:9080/non_ok/SendRedirectGzip.jsp
 */
public void testRedirect() throws Exception {

    String url = "http://localhost:9080/non_ok/SendRedirectGzip.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    //httpclient follows redirects, so gets the home page.
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
}

From source file:com.microsoft.azure.storage.table.QueryTableOperation.java

private StorageRequest<CloudTableClient, QueryTableOperation, TableResult> retrieveImpl(
        final CloudTableClient client, final String tableName, final TableRequestOptions options) {
    final boolean isTableEntry = TableConstants.TABLES_SERVICE_TABLES_NAME.equals(tableName);
    if (this.getClazzType() != null) {
        Utility.checkNullaryCtor(this.getClazzType());
    } else {/*from  w w  w. ja v  a 2 s  . c  om*/
        Utility.assertNotNull(SR.QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER, this.getResolver());
    }

    final StorageRequest<CloudTableClient, QueryTableOperation, TableResult> getRequest = new StorageRequest<CloudTableClient, QueryTableOperation, TableResult>(
            options, client.getStorageUri()) {

        @Override
        public void setRequestLocationMode() {
            this.setRequestLocationMode(isPrimaryOnlyRetrieve() ? RequestLocationMode.PRIMARY_ONLY
                    : RequestLocationMode.PRIMARY_OR_SECONDARY);
        }

        @Override
        public HttpURLConnection buildRequest(CloudTableClient client, QueryTableOperation operation,
                OperationContext context) throws Exception {
            return TableRequest.query(client.getTransformedEndPoint(context).getUri(this.getCurrentLocation()),
                    options, null/* Query Builder */, context, tableName,
                    generateRequestIdentity(isTableEntry, operation.getPartitionKey()),
                    null/* Continuation Token */);
        }

        @Override
        public void signRequest(HttpURLConnection connection, CloudTableClient client, OperationContext context)
                throws Exception {
            StorageRequest.signTableRequest(connection, client, -1L, context);
        }

        @Override
        public TableResult preProcessResponse(QueryTableOperation operation, CloudTableClient client,
                OperationContext context) throws Exception {
            if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK
                    && this.getResult().getStatusCode() != HttpURLConnection.HTTP_NOT_FOUND) {
                this.setNonExceptionedRetryableFailure(true);
            }
            return null;
        }

        @Override
        public TableResult postProcessResponse(HttpURLConnection connection, QueryTableOperation operation,
                CloudTableClient client, OperationContext context, TableResult storageObject) throws Exception {
            if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
                // Empty result
                return new TableResult(this.getResult().getStatusCode());
            }

            // Parse response for updates
            InputStream inStream = connection.getInputStream();
            TableResult res = parseResponse(inStream, this.getResult().getStatusCode(),
                    this.getConnection().getHeaderField(TableConstants.HeaderConstants.ETAG), context, options);

            return res;
        }

        @Override
        public StorageExtendedErrorInformation parseErrorDetails() {
            return TableStorageErrorDeserializer.parseErrorDetails(this);
        }
    };

    return getRequest;
}