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.adyen.httpclient.HttpURLConnectionClient.java

/**
 * Does a POST request with raw body//from  ww w.ja va  2s  .  c o  m
 */
private String doPostRequest(HttpURLConnection httpConnection, String requestBody)
        throws IOException, HTTPClientException {
    String response = null;

    OutputStream outputStream = httpConnection.getOutputStream();
    outputStream.write(requestBody.getBytes());
    outputStream.flush();

    int responseCode = httpConnection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        //Read the response from the error stream
        if (httpConnection.getErrorStream() != null) {
            response = getResponseBody(httpConnection.getErrorStream());
        }

        HTTPClientException httpClientException = new HTTPClientException(responseCode, "HTTP Exception",
                httpConnection.getHeaderFields(), response);

        throw httpClientException;
    }

    //InputStream is only available on successful requests >= 200 <400
    response = getResponseBody(httpConnection.getInputStream());

    // close the connection
    httpConnection.disconnect();

    return response;
}

From source file:com.cloud.agent.AgentShell.java

public static void wget(String url, File file) throws IOException {
    final HttpClient client = new HttpClient(s_httpClientManager);
    final GetMethod method = new GetMethod(url);
    int response;
    response = client.executeMethod(method);
    if (response != HttpURLConnection.HTTP_OK) {
        method.releaseConnection();//w w  w . ja v  a2 s .  co m
        s_logger.warn("Retrieving from " + url + " gives response code: " + response);
        throw new CloudRuntimeException("Unable to download from " + url + ".  Response code is " + response);
    }

    final InputStream is = method.getResponseBodyAsStream();
    s_logger.debug("Downloading content into " + file.getAbsolutePath());

    final FileOutputStream fos = new FileOutputStream(file);
    byte[] buffer = new byte[4096];
    int len = 0;
    while ((len = is.read(buffer)) > 0)
        fos.write(buffer, 0, len);
    fos.close();

    try {
        is.close();
    } catch (IOException e) {
        s_logger.warn("Exception while closing download stream from  " + url + ", ", e);
    }
    method.releaseConnection();
}

From source file:com.flurry.proguard.UploadProGuardMapping.java

/**
 * Call the metadata service to get the project's ID
 *
 * @param apiKey the API key for the project
 * @param token the Flurry auth token/* w w w  .ja  v a 2 s  .  c o m*/
 * @return the project's ID
 */
private static String lookUpProjectId(String apiKey, String token) {
    String queryUrl = String.format("%s/project?fields[project]=apiKey&filter[project.apiKey]=%s",
            METADATA_BASE, apiKey);
    HttpResponse response = executeHttpRequest(new HttpGet(queryUrl), getMetadataHeaders(token));
    expectStatus(response, HttpURLConnection.HTTP_OK);

    JSONObject jsonObject = getJsonFromEntity(response.getEntity());
    JSONArray jsonArray = jsonObject.getJSONArray("data");
    if (jsonArray.length() == 0) {
        failWithError("No projects found for the API Key: " + apiKey);
    }
    return jsonArray.getJSONObject(0).get("id").toString();
}

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

@Test
public void testWithAppIdViaQueryParam() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    httpConfigs.appIdViaQueryParamAllowed = true;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.TEXT,
            new DataParserFormatConfig());
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();/*from w  w w.java2  s  .  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";
        Response response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
        Assert.assertEquals(1, records.size());
        Assert.assertEquals("Hello", records.get(0).get("/text").getValue());

        // Passing wrong App ID in query param should return 403 response
        url = "http://localhost:" + httpConfigs.getPort() + "?" + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM
                + "=wrongid";
        response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getStatus());

        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

From source file:com.google.apphosting.vmruntime.VmApiProxyDelegateTest.java

private void callDelegateWithSuccess(boolean sync) throws Exception {
    RemoteApiPb.Response response = new RemoteApiPb.Response();
    byte[] pbData = new byte[] { 0, 1, 2, 3, 4, 5 };
    response.setResponseAsBytes(pbData);

    HttpClient mockClient = createMockHttpClient();
    HttpResponse mockHttpResponse = createMockHttpResponse(response.toByteArray(), HttpURLConnection.HTTP_OK);
    when(mockClient.execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class)))
            .thenReturn(mockHttpResponse);

    VmApiProxyDelegate delegate = new VmApiProxyDelegate(mockClient);
    VmApiProxyEnvironment environment = createMockEnvironment();

    final Double timeoutInSeconds = 3.0;
    byte[] result = null;
    if (sync) {/*from ww w  . ja  v  a 2s. c o  m*/
        environment.getAttributes().put(VmApiProxyDelegate.API_DEADLINE_KEY, timeoutInSeconds);
        result = delegate.makeSyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, pbData);
    } else {
        ApiConfig apiConfig = new ApiConfig();
        apiConfig.setDeadlineInSeconds(timeoutInSeconds);
        result = delegate.makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, pbData, apiConfig)
                .get();
    }
    assertTrue(Arrays.equals(pbData, result));
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

public byte[] send(byte[] request) {
    while (true) {
        HttpClientContext context = HttpClientContext.create();

        context.setTargetHost(host);//w w  w.  j a va2 s  . com

        // Set the credentials if they were provided.
        if (null != this.credentials) {
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);
            context.setAuthCache(authCache);
        }

        ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);

        // Create the client with the AuthSchemeRegistry and manager
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);

        try (CloseableHttpResponse response = execute(post, context)) {
            final int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == statusCode
                    || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
                return EntityUtils.toByteArray(response.getEntity());
            } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) {
                LOG.debug("Failed to connect to server (HTTP/503), retrying");
                continue;
            }

            throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
        } catch (NoHttpResponseException e) {
            // This can happen when sitting behind a load balancer and a backend server dies
            LOG.debug("The server failed to issue an HTTP response, retrying");
            continue;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Failed to execute HTTP request", e);
            throw new RuntimeException(e);
        }
    }
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

public static String authenticate() throws Exception {
    String token = "";

    /* ***** Authentication ****** */
    String auth = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
            + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP-ENV:Body> <ns1:authenticate xmlns:ns1=\"http://luxid.temis.com/ws/types\"> "
            + "<ns1:userName>" + Config.getConfig().getLuxidUserName() + "</ns1:userName> <ns1:userPassword>"
            + Config.getConfig().getLuxidPassword()
            + "</ns1:userPassword> </ns1:authenticate> </SOAP-ENV:Body> </SOAP-ENV:Envelope>";
    URL authURL = new URL(Config.getConfig().getLuxidServerURL());

    HttpURLConnection authconn = (HttpURLConnection) authURL.openConnection();
    authconn.setRequestMethod("POST");
    authconn.setDoOutput(true);/*from  w w  w.  ja va2  s.c  om*/

    authconn.getOutputStream().write(auth.getBytes());

    if (authconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream stream = authconn.getInputStream();

        InputStreamReader read = new InputStreamReader(stream);
        BufferedReader rd = new BufferedReader(read);

        String line = "";

        if ((line = rd.readLine()) != null) {
            token = line.substring(line.indexOf("<token>") + "<token>".length(), line.indexOf("</token>"));
        }
        rd.close();
    }
    return token;
}

From source file:com.treasure_data.client.bulkimport.BulkImportClientAdaptorImpl.java

private ShowSessionResult doShowSession(ShowSessionRequest request) throws ClientException {
    request.setCredentials(client.getTreasureDataCredentials());
    validator.validateCredentials(client, request);

    String jsonData = null;/*from  ww  w  .  j a va 2s. c o m*/
    String message = null;
    int code = 0;
    try {
        conn = createConnection();
        // send request
        String path = String.format(HttpURL.V3_SHOW, request.getSessionName());
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doGetRequest(request, path, header, params);
        // receive response code and body
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("Show session failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Show session failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "showSession", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("Show session failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    //json data: {
    //  "name":"session_17418",
    //  "status":"committed",
    //  "job_id":17432,
    //  "valid_records":10000000,
    //  "error_records":0,
    //  "valid_parts":39,
    //  "error_parts":0,
    //  "upload_frozen":true,
    //  "database":null,
    //  "table":null}

    @SuppressWarnings("rawtypes")
    Map sess = (Map) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, sess);
    String name = (String) sess.get("name");
    String database = (String) sess.get("database");
    String table = (String) sess.get("table");
    String status = (String) sess.get("status");
    Boolean uf = (Boolean) sess.get("upload_frozen");
    boolean upload_frozen = uf != null ? uf : false;
    String job_id = getJobID(sess);
    Long vr = (Long) sess.get("valid_records");
    long valid_records = vr != null ? vr : 0;
    Long er = (Long) sess.get("error_records");
    long error_records = er != null ? er : 0;
    Long vp = (Long) sess.get("valid_parts");
    long valid_parts = vp != null ? vp : 0;
    Long ep = (Long) sess.get("error_parts");
    long error_parts = ep != null ? ep : 0;

    SessionSummary summary = new SessionSummary(name, database, table, SessionSummary.Status.fromString(status),
            upload_frozen, job_id, valid_records, error_records, valid_parts, error_parts);
    return new ShowSessionResult(summary);
}

From source file:com.googlecode.osde.internal.igoogle.IgCredentials.java

/**
 * Makes a HTTP POST request for authentication.
 *
 * @param emailUserName the name of the user
 * @param password the password of the user
 * @param loginTokenOfCaptcha CAPTCHA token (Optional)
 * @param loginCaptchaAnswer answer of CAPTCHA token (Optional)
 * @return http response as a String//from   ww  w  .j a va  2 s  .c om
 * @throws IOException
 */
// TODO: Refactor requestAuthentication() utilizing HttpPost.
private static String requestAuthentication(String emailUserName, String password, String loginTokenOfCaptcha,
        String loginCaptchaAnswer) throws IOException {

    // Prepare connection.
    URL url = new URL(URL_GOOGLE_LOGIN);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
    logger.fine("url: " + url);

    // Form the POST params.
    StringBuilder params = new StringBuilder();
    params.append("Email=").append(emailUserName).append("&Passwd=").append(password)
            .append("&source=OSDE-01&service=ig&accountType=HOSTED_OR_GOOGLE");
    if (loginTokenOfCaptcha != null) {
        params.append("&logintoken=").append(loginTokenOfCaptcha);
    }
    if (loginCaptchaAnswer != null) {
        params.append("&logincaptcha=").append(loginCaptchaAnswer);
    }

    // Send POST via output stream.
    OutputStream outputStream = null;
    try {
        outputStream = urlConnection.getOutputStream();
        outputStream.write(params.toString().getBytes(IgHttpUtil.ENCODING));
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // Retrieve response.
    // TODO: Should the caller of this method need to know the responseCode?
    int responseCode = urlConnection.getResponseCode();
    logger.fine("responseCode: " + responseCode);
    InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? urlConnection.getInputStream()
            : urlConnection.getErrorStream();

    logger.fine("inputStream: " + inputStream);
    try {
        String response = IOUtils.toString(inputStream, IgHttpUtil.ENCODING);
        return response;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}