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:org.opencastproject.capture.impl.jobs.AgentStateJob.java

/**
 * Utility method to POST data to a URL. This method encodes the data in UTF-8 as post data, rather than multipart
 * MIME./*from   ww  w  . j  a  v a 2s  .  com*/
 * 
 * @param formParams
 *          The data to send.
 * @param url
 *          The URL to send the data to.
 */
private void send(List<NameValuePair> formParams, String url) {
    HttpResponse resp = null;
    HttpPost remoteServer = new HttpPost(url);
    try {
        remoteServer.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        logger.error(
                "#" + statePushCount + " - Unable to send data because the URL encoding is not supported.");
        return;
    }
    try {
        if (client == null) {
            logger.error("#" + statePushCount + " - Unable to send data because http client is null.");
            return;
        }

        resp = client.execute(remoteServer);
        if (resp.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            logger.info("#" + statePushCount + " - State push to " + toString() + " to {} failed with code {}.",
                    url, resp.getStatusLine().getStatusCode());
        } else {
            logger.debug("#" + statePushCount + " - State push {} to {} was successful.", toString(), url);
        }
    } catch (TrustedHttpClientException e) {
        logger.warn("#" + statePushCount + " - Unable to communicate with server at {}, message reads: {}.",
                url, e);
    } finally {
        if (resp != null) {
            client.close(resp);
        }
    }
}

From source file:com.flurry.proguard.UploadMapping.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//from w ww.ja  v a 2s.c o  m
 * @return the project's ID
 */
private static String lookUpProjectId(String apiKey, String token) throws IOException {
    String queryUrl = String.format("%s/project?fields[project]=apiKey&filter[project.apiKey]=%s",
            METADATA_BASE, apiKey);
    JSONObject jsonObject;
    try (CloseableHttpResponse response = executeHttpRequest(new HttpGet(queryUrl),
            getMetadataHeaders(token))) {
        expectStatus(response, HttpURLConnection.HTTP_OK);
        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:org.jboss.as.test.integration.web.sso.SSOTestBase.java

public static void executeFormLogin(HttpClient httpConn, URL warURL) throws IOException {
    // Submit the login form
    HttpPost formPost = new HttpPost(warURL + "j_security_check");
    formPost.addHeader("Referer", warURL + "login.html");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", "user1"));
    formparams.add(new BasicNameValuePair("j_password", "password1"));
    formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

    HttpResponse postResponse = httpConn.execute(formPost);

    int statusCode = postResponse.getStatusLine().getStatusCode();
    Header[] errorHeaders = postResponse.getHeaders("X-NoJException");
    assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode,
            statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
    EntityUtils.consume(postResponse.getEntity());

    // Follow the redirect to the index.html page
    String indexURL = postResponse.getFirstHeader("Location").getValue();
    HttpGet rediretGet = new HttpGet(indexURL.toString());
    HttpResponse redirectResponse = httpConn.execute(rediretGet);

    statusCode = redirectResponse.getStatusLine().getStatusCode();
    errorHeaders = redirectResponse.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    String body = EntityUtils.toString(redirectResponse.getEntity());
    assertTrue("Get of " + indexURL + " redirected to login page", body.indexOf("j_security_check") < 0);
}

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {/* www  .j av  a  2 s  .  c o  m*/
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}

From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSink2Test.java

/**
 * Test that the deferredTask handler is installed.
 *//*from w ww. j  a  v a 2s  .com*/
public void testDeferredTask() throws Exception {
    // Replace the API proxy delegate so we can fake API responses.
    FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
    ApiProxy.setDelegate(fakeApiProxy);

    // Add a api response so the task queue api is happy.
    TaskQueueBulkAddResponse taskAddResponse = new TaskQueueBulkAddResponse();
    TaskResult taskResult = taskAddResponse.addTaskResult();
    taskResult.setResult(ErrorCode.OK.getValue());
    taskResult.setChosenTaskName("abc");
    fakeApiProxy.addApiResponse(taskAddResponse);

    // Issue a deferredTaskRequest with payload.
    String testData = "0987654321acbdefghijklmn";
    String[] lines = fetchUrl(createUrl("/testTaskQueue?deferredTask=1&deferredData=" + testData));
    TaskQueueBulkAddRequest request = new TaskQueueBulkAddRequest();
    request.parseFrom(fakeApiProxy.getLastRequest().requestData);
    assertEquals(1, request.addRequestSize());
    TaskQueueAddRequest addRequest = request.getAddRequest(0);
    assertEquals(TaskQueueAddRequest.RequestMethod.POST.getValue(), addRequest.getMethod());

    // Pull out the request and fire it at the app.
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    PostMethod post = new PostMethod(createUrl(addRequest.getUrl()).toString());
    post.getParams().setVersion(HttpVersion.HTTP_1_0);
    // Add the required Task queue header, plus any headers from the request.
    post.addRequestHeader("X-AppEngine-QueueName", "1");
    for (TaskQueueAddRequest.Header header : addRequest.headers()) {
        post.addRequestHeader(header.getKey(), header.getValue());
    }
    post.setRequestEntity(new ByteArrayRequestEntity(addRequest.getBodyAsBytes()));
    int httpCode = httpClient.executeMethod(post);
    assertEquals(HttpURLConnection.HTTP_OK, httpCode);

    // Verify that the task was handled and that the payload is correct.
    lines = fetchUrl(createUrl("/testTaskQueue?getLastPost=1"));
    assertEquals("deferredData:" + testData, lines[lines.length - 1]);
}

From source file:de.ub0r.android.websms.connector.fishtext.ConnectorFishtext.java

/**
 * Prepare send.//from w  ww  .  j a v  a 2  s  .c o  m
 * 
 * @param context
 *            {@link Context}
 * @param command
 *            {@link ConnectorCommand}
 * @param throwOnFail
 *            throw exception on fail, if false a fresh session is loaded
 *            for retry
 * @return messageID
 * @throws IOException
 *             IOException
 */
private String getMessageID(final Context context, final ConnectorCommand command, final boolean throwOnFail)
        throws IOException {
    if (Utils.getCookieCount() == 0) {
        this.doLogin(context, command);
    }
    final HttpResponse response = Utils.getHttpClient(URL_PRESEND, null, new ArrayList<BasicNameValuePair>(0),
            TARGET_AGENT, URL_LOGIN, ENCODING, false);
    final int resp = response.getStatusLine().getStatusCode();
    if (resp != HttpURLConnection.HTTP_OK) {
        throw new WebSMSException(context, R.string.error_http, "" + resp);
    }
    String htmlText = Utils.stream2str(response.getEntity().getContent());
    // , STRIP_PRESEND_START, STRIP_PRESEND_END);
    Log.d(TAG, "----HTTP RESPONSE---");
    Log.d(TAG, htmlText);
    Log.d(TAG, "----HTTP RESPONSE---");
    final int i = htmlText.indexOf(CHECK_PRESEND);
    if (i < 0) {
        if (throwOnFail) {
            Utils.clearCookies();
            Log.e(TAG, "presend check failed, response following:");
            Log.e(TAG, htmlText);
            throw new WebSMSException(context, R.string.error_service);
        } else {
            // try again with fresh session
            this.doLogin(context, command);
            return this.getMessageID(context, command, true);
        }
    }
    int j = htmlText.indexOf("name=", i);
    if (j < 0) {
        Log.e(TAG, "did not found \"name=\", response following:");
        Log.e(TAG, htmlText);
        throw new WebSMSException(context, R.string.error_service);
    }
    Log.d(TAG, "j = " + j);
    htmlText = htmlText.substring(j + 6);
    j = htmlText.indexOf("\"", 1);
    if (j < 0) {
        Log.e(TAG, "did not found \'\"\', response following:");
        Log.e(TAG, htmlText);
        throw new WebSMSException(context, R.string.error_service);
    }
    final String messageID = htmlText.substring(0, j);
    htmlText = null;
    Log.d(TAG, "message id: " + messageID);
    return messageID;
}

From source file:cz.incad.kramerius.k5indexer.Commiter.java

/**
 * Reads data from the data reader and posts it to solr, writes the response
 * to output/*  w  w w . j a va  2s.  com*/
 */
private void postData(URL url, Reader data, String contentType, StringBuilder output) throws Exception {
    HttpURLConnection urlc = null;

    try {
        urlc = (HttpURLConnection) url.openConnection();
        urlc.setConnectTimeout(config.getInt("http.timeout", 10000));
        try {
            urlc.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlc.setDoOutput(true);
        urlc.setDoInput(true);
        urlc.setUseCaches(false);
        urlc.setAllowUserInteraction(false);
        urlc.setRequestProperty("Content-type", contentType);

        OutputStream out = urlc.getOutputStream();

        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            pipe(data, writer);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        InputStream in = urlc.getInputStream();
        int status = urlc.getResponseCode();
        StringBuilder errorStream = new StringBuilder();
        try {
            if (status != HttpURLConnection.HTTP_OK) {
                errorStream.append("postData URL=").append(solrUrl).append(" HTTP response code=")
                        .append(status).append(" ");
                throw new Exception("URL=" + solrUrl + " HTTP response code=" + status);
            }
            Reader reader = new InputStreamReader(in);
            pipeString(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null) {
                in.close();
            }
        }

        InputStream es = urlc.getErrorStream();
        if (es != null) {
            try {
                Reader reader = new InputStreamReader(es);
                pipeString(reader, errorStream);
                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (es != null) {
                    es.close();
                }
            }
        }
        if (errorStream.length() > 0) {
            throw new Exception("postData error: " + errorStream.toString());
        }

    } catch (IOException e) {
        throw new Exception("Solr has throw an error. Check tomcat log. " + e);
    } finally {
        if (urlc != null) {
            urlc.disconnect();
        }
    }
}

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

private void callDelegateWithOneError(boolean sync, RemoteApiPb.RpcError rpcError,
        RemoteApiPb.ApplicationError appError, ApiProxyException expectedException) throws Exception {
    // Create the response for the mock connection.
    RemoteApiPb.Response response = new RemoteApiPb.Response();
    if (appError != null) {
        response.setApplicationError(appError);
    }//ww w.j  a  va2s.  co m
    if (rpcError != null) {
        response.setRpcError(rpcError);
    }

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

    byte[] requestData = new byte[] { 0, 1, 2, 3, 4, 5 };
    byte[] result = null;
    final Double timeoutInSeconds = 10.0;

    if (sync) {
        try {
            environment.getAttributes().put(VmApiProxyDelegate.API_DEADLINE_KEY, timeoutInSeconds);
            result = delegate.makeSyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, requestData);
            fail();
        } catch (ApiProxyException exception) {
            assertEquals(expectedException.getClass(), exception.getClass());
        }
    } else {
        try {
            ApiConfig apiConfig = new ApiConfig();
            apiConfig.setDeadlineInSeconds(timeoutInSeconds);
            result = delegate
                    .makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, requestData, apiConfig)
                    .get();
            fail();
        } catch (ExecutionException exception) {
            // ExecutionException is expected, and make sure the cause is expected as well.
            assertEquals(expectedException.getClass(), exception.getCause().getClass());
        }
    }
    assertNull(result);
}

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<Playground> getNearby(Context context, GeoPoint location, int maxQuantity) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {/*from   ww  w .j  a va  2  s. co m*/
        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground?" + TYPE_PARAM + "=" + NEARBY + "&"
                + LATITUDE_PARAM + "=" + location.getLatitudeE6() + "&" + LONGITUDE_PARAM + "="
                + location.getLongitudeE6() + "&" + MAX_PARAM + "=" + Integer.toString(maxQuantity));
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    Log.d(TAG, "   -> returned " + result);
    return playgrounds;

}

From source file:com.exzogeni.dk.http.HttpTask.java

@SuppressWarnings("checkstyle:illegalcatch")
private V onSuccessInternal(HttpURLConnection cn) throws Exception {
    try {// w w  w .j a v a2  s .c  o m
        final URI uri = getEncodedUriInternal();
        final Map<String, List<String>> headers = getHeaderFields(cn);
        final CookieManager cookieManager = mHttpManager.getCookieManager();
        final CacheManager cacheManager = mHttpManager.getCacheManager();
        cookieManager.put(uri, headers);
        final int responseCode = cn.getResponseCode();
        InputStream content = getInputStream(cn);
        if (responseCode == HttpURLConnection.HTTP_OK && mCachePolicy.shouldCache(uri)) {
            content = cacheManager.put(uri, headers, content);
        } else if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED && mCachePolicy.shouldCache(uri)) {
            content = cacheManager.update(uri, headers);
        }
        return onSuccessInternal(responseCode, headers, content);
    } catch (Exception e) {
        throw onException(new HttpException(getEncodedUrlInternal(), e));
    }
}