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.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;/*  w ww .  j a  v a 2s. c  om*/
    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:mobi.jenkinsci.ci.client.sso.GoogleSsoHandler.java

@Override
public String doTwoStepAuthentication(final HttpClient httpClient, final HttpContext httpContext,
        final HttpResponse response, final String otp) throws IOException {
    final HttpPost formPost = getOtpFormPost(httpContext, response, otp);
    Element otpResponseForm;/*from  w  w  w .  java 2 s .c om*/
    try {
        final HttpResponse otpResponse = httpClient.execute(formPost, httpContext);
        if (otpResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            throw getException(otpResponse);
        }

        final Document otpResponseDoc = Jsoup.parse(otpResponse.getEntity().getContent(), "UTF-8", "");
        otpResponseForm = otpResponseDoc.select("form[id=hiddenpost]").first();
        if (otpResponseForm == null) {
            final Element errorDiv = otpResponseDoc.select("div[id=error]").first();
            if (errorDiv == null) {
                throw new IOException(
                        "2nd-step authentication FAILED: Google did not return positive response form.");
            } else {
                throw new TwoPhaseAuthenticationRequiredException(getDivText(errorDiv),
                        GOOGLE_ANDROID_APPS_AUTHENTICATOR2_APP_ID);
            }
        }
    } finally {
        formPost.releaseConnection();
    }

    final HttpPost formCompletePost = JenkinsFormAuthHttpClient
            .getPostForm(JenkinsFormAuthHttpClient.getLatestRedirectedUrl(httpContext), otpResponseForm, null);
    try {
        final HttpResponse otpCompleteResponse = httpClient.execute(formCompletePost, httpContext);
        if (otpCompleteResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) {
            throw new IOException(
                    String.format("2nd-step authentication failed: Google returned HTTP-Status:%d %s",
                            otpCompleteResponse.getStatusLine().getStatusCode(),
                            otpCompleteResponse.getStatusLine().getReasonPhrase()));
        }

        return otpCompleteResponse.getFirstHeader("Location").getValue();
    } finally {
        formCompletePost.releaseConnection();
    }
}

From source file:com.uisteps.utils.api.rest.RestApiRequest.java

public RestApiResponse send(Method method, Object request) throws RestApiException {

    HttpURLConnection connection = null;
    String url = host;//from w w  w .jav a 2  s . com

    if (isJSON(request) || method == Method.DELETE) {
        setProperty("Content-Type", "application/json");
    }

    try {

        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod(method.toString());

        for (String key : headers.keySet()) {
            connection.setRequestProperty(key, headers.get(key));
        }

        if (method != Method.GET) {
            connection.setDoOutput(true);
            OutputStream writer = new BufferedOutputStream(connection.getOutputStream());
            writer.write(this.request.toString().getBytes(responseEncoding));
            writer.flush();
        }

        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            String response = readStreamToString(connection.getInputStream(), responseEncoding);
            return new RestApiResponse(response);
        } else {
            throw new RestApiException("Connection is broken!").setResponseCode(responseCode);
        }

    } catch (IOException ex) {

        throw new RestApiException("Cannot send to " + host + " request:\n" + request + "\n" + ex);

    } catch (RestApiException ex) {

        throw new RestApiException("Cannot send to " + host + " request:\n" + request + "\n" + ex)
                .setResponseCode(ex.getResponseCode());

    } finally {

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

From source file:com.facebook.buck.rules.HttpArtifactCache.java

public CacheResult fetchImpl(RuleKey ruleKey, File file) throws IOException {
    Request request = createRequestBuilder(ruleKey.toString()).get().build();
    Response response = fetchCall(request);

    if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) {
        LOGGER.info("fetch(%s): cache miss", ruleKey);
        return CacheResult.MISS;
    }/*w w w .  j  a  va2s .c om*/

    if (response.code() != HttpURLConnection.HTTP_OK) {
        LOGGER.warn("fetch(%s): unexpected response: %d", ruleKey, response.code());
        return CacheResult.MISS;
    }

    // The hash code shipped with the artifact to/from the cache.
    HashCode expectedHashCode, actualHashCode;

    // Setup a temporary file, which sits next to the destination, to write to and
    // make sure all parent dirs exist.
    Path path = file.toPath();
    projectFilesystem.createParentDirs(path);
    Path temp = projectFilesystem.createTempFile(path.getParent(), path.getFileName().toString(), ".tmp");

    // Open the stream to server just long enough to read the hash code and artifact.
    try (DataInputStream input = new DataInputStream(response.body().byteStream())) {

        // First, extract the size of the file data portion, which we put in the beginning of
        // the artifact.
        long length = input.readLong();

        // Now, write the remaining response data to the temp file, while grabbing the hash.
        try (BoundedInputStream boundedInput = new BoundedInputStream(input, length);
                HashingInputStream hashingInput = new HashingInputStream(hashFunction, boundedInput);
                OutputStream output = projectFilesystem.newFileOutputStream(temp)) {
            ByteStreams.copy(hashingInput, output);
            actualHashCode = hashingInput.hash();
        }

        // Lastly, extract the hash code from the end of the request data.
        byte[] hashCodeBytes = new byte[hashFunction.bits() / Byte.SIZE];
        ByteStreams.readFully(input, hashCodeBytes);
        expectedHashCode = HashCode.fromBytes(hashCodeBytes);

        // We should be at the end of output -- verify this.  Also, we could just try to read a
        // single byte here, instead of all remaining input, but some network stack implementations
        // require that we exhaust the input stream before the connection can be reusable.
        try (OutputStream output = ByteStreams.nullOutputStream()) {
            if (ByteStreams.copy(input, output) != 0) {
                LOGGER.warn("fetch(%s): unexpected end of input", ruleKey);
                return CacheResult.MISS;
            }
        }
    }

    // Now form the checksum on the file we got and compare it to the checksum form the
    // the HTTP header.  If it's incorrect, log this and return a miss.
    if (!expectedHashCode.equals(actualHashCode)) {
        LOGGER.warn("fetch(%s): artifact had invalid checksum", ruleKey);
        projectFilesystem.deleteFileAtPath(temp);
        return CacheResult.MISS;
    }

    // Finally, move the temp file into it's final place.
    projectFilesystem.move(temp, path, StandardCopyOption.REPLACE_EXISTING);

    LOGGER.info("fetch(%s): cache hit", ruleKey);
    return CacheResult.HTTP_HIT;
}

From source file:de.xwic.appkit.core.remote.client.URemoteAccessClient.java

/**
 * @param param/*from  www .j  a v a  2 s.  c  om*/
 * @param config
 * @return
 */
public static byte[] postRequest(final IRequestHelper helper, final RemoteSystemConfiguration config) {
    CloseableHttpResponse response = null;
    try {

        CloseableHttpClient client = PoolingHttpConnectionManager.getInstance().getClientInstance(config);
        HttpPost post = new HttpPost(helper.getTargetUrl());
        post.setEntity(helper.getHttpEntity());

        response = client.execute(post);

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new RemoteDataAccessException(response.getStatusLine().getReasonPhrase());
        }
        return EntityUtils.toByteArray(response.getEntity());
    } catch (RemoteDataAccessException re) {
        throw re;
    } catch (Exception e) {
        throw new RemoteDataAccessException(e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

From source file:org.jboss.as.test.integration.management.console.XFrameOptionsHeaderTestCase.java

private void checkURLForHeader(URL url, String headerName, String expectedHeaderValue)
        throws URISyntaxException, IOException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(createCredentialsProvider(url)).build()) {
        HttpContext httpContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(httpGet, httpContext);

        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Wrong response code: " + statusCode + " for url '" + url.toString() + "'.",
                HttpURLConnection.HTTP_OK, statusCode);

        Header[] headers = response.getHeaders(headerName);
        assertNotNull("Unexpected behaviour of HttpResponse#getHeaders() returned null!", headers);
        assertTrue("There is no '" + headerName + "' header present! Headers present: "
                + Arrays.toString(response.getAllHeaders()), headers.length > 0);
        for (Header header : headers) {
            if (header.getValue().equals(expectedHeaderValue)) {
                return;
            }/*from   w w w  . j a  v a 2s  . c o  m*/
        }
        fail("No header '" + headerName + "' with value '" + expectedHeaderValue + "' found!");
    }
}

From source file:org.mobisocial.corral.CorralS3Connector.java

public void uploadToServer(String ticket, final EncRslt rslt, String datestr, String objName,
        final UploadProgressCallback callback) throws ClientProtocolException, IOException {
    callback.onProgress(UploadState.PREPARING_UPLOAD, 0);
    Log.d(TAG, "-----UPLOAD START-----");
    Log.d(TAG, "URI: " + rslt.uri.toString());
    Log.d(TAG, "length: " + rslt.length);
    Log.d(TAG, "ticket: " + ticket);
    Log.d(TAG, SERVER_URL + objName);
    Log.d(TAG, "Authorization: AWS " + ticket);
    Log.d(TAG, "Content-Md5: " + rslt.md5);
    Log.d(TAG, "Content-Type: " + CONTENT_TYPE);
    Log.d(TAG, "Date: " + datestr);

    InputStream in = mContext.getContentResolver().openInputStream(rslt.uri);
    final int contentLength = in.available();

    HttpClient http = new DefaultHttpClient();
    HttpPut put = new HttpPut(SERVER_URL + objName);

    put.setHeader("Authorization", "AWS " + ticket);
    put.setHeader("Content-Md5", rslt.md5);
    put.setHeader("Content-Type", CONTENT_TYPE);
    put.setHeader("Date", datestr);

    HttpEntity progress = new ProgressEntity(callback, rslt, contentLength);

    put.setEntity(progress);/*w w w.  j a v a2 s  . com*/
    HttpResponse response = http.execute(put);
    final int responseCode = response.getStatusLine().getStatusCode();

    // FOR DEBUG
    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException("invalid response code, " + responseCode);
    }
}

From source file:be.fedict.trust.crl.OnlineCrlRepository.java

private X509CRL getCrl(URI crlUri) throws IOException, CertificateException, CRLException,
        NoSuchProviderException, NoSuchParserException, StreamParsingException {
    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }//  w  ww . j a  v  a  2 s . co  m
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }
    String downloadUrl = crlUri.toURL().toString();
    LOG.debug("downloading CRL from: " + downloadUrl);
    GetMethod getMethod = new GetMethod(downloadUrl);
    getMethod.addRequestHeader("User-Agent", "jTrust CRL Client");
    int statusCode = httpClient.executeMethod(getMethod);
    if (HttpURLConnection.HTTP_OK != statusCode) {
        LOG.debug("HTTP status code: " + statusCode);
        return null;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509CRL crl = (X509CRL) certificateFactory.generateCRL(getMethod.getResponseBodyAsStream());
    LOG.debug("CRL size: " + crl.getEncoded().length + " bytes");
    return crl;
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?//from  ww  w. j a v a2s .  c  om
 * @param postUrl ?
 * @param param ?
 * @param method 
 * @return null
 */
public static String request(String postUrl, String param, String method) {
    URL url;
    try {
        url = new URL(postUrl);

        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000); // ??)
        conn.setReadTimeout(30000); // ????)
        conn.setDoOutput(true); // post??http?truefalse
        conn.setDoInput(true); // ?httpUrlConnectiontrue
        conn.setUseCaches(false); // Post ?
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);// "POST"GET
        conn.setRequestProperty("Content-Length", param.length() + "");
        String encode = "utf-8";
        OutputStreamWriter out = null;
        out = new OutputStreamWriter(conn.getOutputStream(), encode);
        out.write(param);
        out.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // ??
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        in.close();
        out.close();
        return strBuf.toString();
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:org.opencastproject.loadtest.impl.JobChecker.java

/**
 * Use the TrustedHttpClient from matterhorn to check the status of jobs. 
 * //  ww  w  .java  2s.  c o  m
 * @param id
 *          The media package id to check. 
 * @param mediaPackageLocation
 *          The location of the mediapackage we want to ingest.
 */
private void checkJobWithJava(IngestJob job) {
    String id = job.getID();
    logger.info("Checking recording: {}", id);
    try {
        URL url = new URL(loadTest.getCoreAddress() + "/workflow/instance/" + id);
        logger.debug("Check Job URL is " + url.toString());
        HttpGet getMethod = new HttpGet(url.toString());

        // Send the request
        HttpResponse response = null;
        int retValue = -1;
        try {
            response = client.execute(getMethod);
        } catch (TrustedHttpClientException e) {
            logger.error("Unable to check ingest {}, message reads: {}.", id, e.getMessage());
        } catch (NullPointerException e) {
            logger.error("Unable to check ingest {}, null pointer exception!", id);
        } finally {
            if (response != null) {
                retValue = response.getStatusLine().getStatusCode();
                client.close(response);
            } else {
                retValue = -1;
            }
        }

        if (retValue == HttpURLConnection.HTTP_OK) {
            logger.info(id + " successfully ingested, is now processing and will be marked as done.");
            ingestJobs.remove(job);
            ThreadCounter.subtract();
        } else {
            logger.info(id + " has not ingested yet.");
        }

    } catch (MalformedURLException e) {
        logger.error("Malformed URL for ingest target \"" + loadTest.getCoreAddress()
                + "/ingest/addZippedMediaPackage\"");
    }
}