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.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestPostNewTask.java

@Override
protected BugzillaRestIdResult doProcess(CommonHttpResponse response, IOperationMonitor monitor)
        throws IOException, BugzillaRestException {
    InputStream is = response.getResponseEntityAsStream();
    InputStreamReader in = new InputStreamReader(is);
    switch (response.getStatusCode()) {
    case HttpURLConnection.HTTP_OK:
        return parseFromJson(in);
    default:/*  www.  ja  va 2  s . c  om*/
        BugzillaRestStatus status = parseErrorFromJson(in);
        throw new BugzillaRestException(
                NLS.bind("{2}  (status: {1} from {0})", new String[] { response.getRequestPath(),
                        HttpUtil.getStatusText(response.getStatusCode()), status.getMessage() }));
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMV2.java

private static List<String> connectAndReadFromURL(URL url, String fileName, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/*  www .j av  a2  s  . com*/
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair("serverManifestLoc", fileName));
        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("!!!!!Response code for requesting datda file:
        // " + responseCode);

        if (responseCode != HttpURLConnection.HTTP_OK) {
            return null;
        } else {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java

@Test
public void testHttpRandomPort() throws Exception {
    Configuration conf = new Configuration();
    conf.set(WebServerTask.AUTHENTICATION_KEY, "none");
    conf.set(WebServerTask.HTTP_PORT_KEY, 0);
    final WebServerTask ws = createWebServerTask(createTestDir(), conf);
    try {/* w ww  .  j  ava 2 s  .  c om*/
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        Thread.sleep(1000);

        HttpURLConnection conn = (HttpURLConnection) new URL(
                "http://127.0.0.1:" + ws.getServerURI().getPort() + "/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    } finally {
        ws.stopTask();
    }
}

From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;// ww w  .  j  av  a  2s . 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.connect();

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

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, BTCE_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + BTCE_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.rimbit.android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;// w ww  . j a v a  2  s . com

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

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

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

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

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

    return null;

}

From source file:forge.download.GuiDownloadService.java

@Override
public void run() {

    Proxy p = getProxy();/*from w ww  .ja  v  a  2 s  . c om*/

    int bufferLength;
    int iCard = 0;
    byte[] buffer = new byte[1024];

    for (Entry<String, String> kv : files.entrySet()) {
        if (cancel) {
            break;
        }

        String url = kv.getValue();
        final File fileDest = new File(kv.getKey());
        final File base = fileDest.getParentFile();

        FileOutputStream fos = null;
        try {
            // test for folder existence
            if (!base.exists() && !base.mkdir()) { // create folder if not found
                System.out.println("Can't create folder" + base.getAbsolutePath());
            }

            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(p);
            // don't allow redirections here -- they indicate 'file not found' on the server
            conn.setInstanceFollowRedirects(false);
            conn.connect();

            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                conn.disconnect();
                System.out.println(url);
                System.out.println("Skipped Download for: " + fileDest.getPath());
                update(++iCard, fileDest);
                skipped++;
                continue;
            }

            fos = new FileOutputStream(fileDest);
            InputStream inputStream = conn.getInputStream();
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fos.write(buffer, 0, bufferLength);
            }
        } catch (final ConnectException ce) {
            System.out.println("Connection refused for url: " + url);
        } catch (final MalformedURLException mURLe) {
            System.out.println("Error - possibly missing URL for: " + fileDest.getName());
        } catch (final FileNotFoundException fnfe) {
            String formatStr = "Error - the LQ picture %s could not be found on the server. [%s] - %s";
            System.out.println(String.format(formatStr, fileDest.getName(), url, fnfe.getMessage()));
        } catch (final Exception ex) {
            Log.error("LQ Pictures", "Error downloading pictures", ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    System.out.println("error closing output stream");
                }
            }
        }

        update(++iCard, fileDest);

    }
}

From source file:com.matthewmitchell.nubits_android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;/*from  www  .j  a v a 2 s.  co 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.connect();

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

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } 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.mobile.godot.core.controller.CoreController.java

public synchronized void findCarsByOwner(String username) {

    String servlet = "FindCarsByOwner";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.CARS_BY_OWNER_FOUND);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Error.NOT_FOUND);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();/*from w w  w  . j  ava 2  s  . co  m*/

}

From source file:de.ub0r.android.websms.connector.o2.ConnectorO2.java

/**
 * Load captcha and wait for user input to solve it.
 * /*from www  . jav  a 2s .  com*/
 * @param context
 *            {@link Context}
 * @param flow
 *            _flowExecutionKey
 * @return true if captcha was solved
 * @throws IOException
 *             IOException
 */
private boolean solveCaptcha(final Context context, final String flow) throws IOException {
    HttpResponse response = Utils.getHttpClient(URL_CAPTCHA, null, null, TARGET_AGENT, URL_LOGIN, ENCODING,
            O2_SSL_FINGERPRINTS);
    int resp = response.getStatusLine().getStatusCode();
    if (resp != HttpURLConnection.HTTP_OK) {
        throw new WebSMSException(context, R.string.error_http, "" + resp);
    }
    BitmapDrawable captcha = new BitmapDrawable(response.getEntity().getContent());
    final Intent intent = new Intent(Connector.ACTION_CAPTCHA_REQUEST);
    intent.putExtra(Connector.EXTRA_CAPTCHA_DRAWABLE, captcha.getBitmap());
    captcha = null;
    this.getSpec(context).setToIntent(intent);
    context.sendBroadcast(intent);
    try {
        synchronized (CAPTCHA_SYNC) {
            CAPTCHA_SYNC.wait(CAPTCHA_TIMEOUT);
        }
    } catch (InterruptedException e) {
        Log.e(TAG, null, e);
        return false;
    }
    if (captchaSolve == null) {
        return false;
    }
    // got user response, try to solve captcha
    Log.d(TAG, "got solved captcha: " + captchaSolve);
    final ArrayList<BasicNameValuePair> postData = // .
            new ArrayList<BasicNameValuePair>(3);
    postData.add(new BasicNameValuePair("_flowExecutionKey", flow));
    postData.add(new BasicNameValuePair("_eventId", "submit"));
    postData.add(new BasicNameValuePair("riddleValue", captchaSolve));
    response = Utils.getHttpClient(URL_SOLVECAPTCHA, null, postData, TARGET_AGENT, URL_LOGIN, ENCODING,
            O2_SSL_FINGERPRINTS);
    Log.d(TAG, postData.toString());
    resp = response.getStatusLine().getStatusCode();
    if (resp != HttpURLConnection.HTTP_OK) {
        throw new WebSMSException(context, R.string.error_http, "" + resp);
    }
    final String mHtmlText = Utils.stream2str(response.getEntity().getContent());
    if (mHtmlText.indexOf(CHECK_WRONGCAPTCHA) > 0) {
        throw new WebSMSException(context, R.string.error_wrongcaptcha);
    }
    return true;
}