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:io.undertow.integration.test.rootcontext.RootContextUtil.java

/**
 * Access http://localhost//*from  w ww.  jav  a  2 s.c  o  m*/
 */
public static String hitRootContext(Logger log, URL url, String serverName) throws Exception {
    HttpGet httpget = new HttpGet(url.toURI());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpget.setHeader("Host", serverName);

    log.info("executing request" + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

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

    return EntityUtils.toString(response.getEntity());
}

From source file:rogerthat.topdesk.bizz.Util.java

public static String topdeskAPIPost(String apiKey, String path, JSONObject jsonData)
        throws IOException, ParseException {
    final Settings settings = Settings.get();
    URL url = new URL(settings.get("TOPDESK_API_URL") + path);
    HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30));
    request.setPayload(jsonData.toString().getBytes("UTF-8"));
    String authHeader = "TOKEN id=\"" + apiKey + "\"";
    log.info("Authorization header: " + authHeader);
    request.addHeader(new HTTPHeader("Authorization", authHeader));
    request.addHeader(new HTTPHeader("Content-type", "application/json"));
    request.addHeader(new HTTPHeader("Accept", "application/json"));
    URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
    HTTPResponse response = urlFetch.fetch(request);
    String content = getContent(response);
    int responseCode = response.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new TopdeskApiException(
                "POST to " + path + " failed with response code " + responseCode + "\nContent:" + content);
    }//  w w  w .  jav a2s.  com
    return content;
}

From source file:de.egore911.versioning.deployer.performer.PerformCopy.java

private boolean copy(String uri, String target, String targetFilename) {
    URL url;/*w  ww  .  j ava  2  s .co  m*/
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        String filename;
        if (StringUtils.isEmpty(targetFilename)) {
            filename = uri.substring(lastSlash + 1);
        } else {
            filename = targetFilename;
        }

        XmlHolder xmlHolder = XmlHolder.getInstance();
        XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()");

        if (response == HttpURLConnection.HTTP_OK) {
            String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename);

            File downloadFile = new File(downloadFilename);
            FileUtils.forceMkdir(downloadFile.getParentFile());
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFilename)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFilename);

            if (StringUtils.isEmpty(targetFilename)) {
                // Check if finalName if exists in pom.xml
                String destFile = null;
                try (ZipFile zipFile = new ZipFile(downloadFilename)) {
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        if (entry.getName().endsWith("/pom.xml")) {

                            String finalNameInPom;
                            try (InputStream inputStream = zipFile.getInputStream(entry)) {
                                try {
                                    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
                                    Model model = mavenreader.read(inputStream);
                                    finalNameInPom = model.getBuild().getFinalName();
                                } catch (Exception e) {
                                    Document doc = xmlHolder.documentBuilder.parse(inputStream);
                                    finalNameInPom = (String) finalNameXpath.evaluate(doc,
                                            XPathConstants.STRING);
                                }
                            }

                            if (StringUtils.isNotEmpty(finalNameInPom)) {
                                destFile = UrlUtil.concatenateUrlWithSlashes(target,
                                        finalNameInPom + "." + uri.substring(lastDot + 1));
                            }
                            break;
                        }
                    }
                }

                // Move file to finalName if existed in pom.xml
                if (destFile != null) {
                    try {
                        File dest = new File(destFile);
                        if (dest.exists()) {
                            FileUtils.forceDelete(dest);
                        }
                        FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile());
                        LOG.debug("Moved file from {} to {}", downloadFilename, destFile);
                    } catch (IOException e) {
                        LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e);
                    }
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e);
        return false;
    }
}

From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address address) {
    backgroundHandler.post(new Runnable() {
        @Override// ww w  .  j a  v a  2s.c  om
        public void run() {
            // Use either dogechain or chain.so
            List<String> urls = new ArrayList<String>(2);
            urls.add(Constants.DOGECHAIN_API_URL);
            urls.add(Constants.CHAINSO_API_URL);
            Collections.shuffle(urls, new Random(System.nanoTime()));

            final StringBuilder url = new StringBuilder(urls.get(0));
            url.append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int success = json.getInt("success");
                    if (success != 1)
                        throw new IOException("api status " + success + " when fetching unspent outputs");

                    final JSONArray jsonOutputs = json.getJSONArray("unspent_outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("tx_hash"));
                        final int uxtoIndex = jsonOutput.getInt("tx_output_n");
                        final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

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

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void addCar(CarBean car) {

    String servlet = "AddCar";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("carName", car.getName()));
    params.add(new BasicNameValuePair("username", car.getOwnerUsername()));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.CAR_CREATED);
    mMessageMap.append(HttpURLConnection.HTTP_CONFLICT, GodotMessage.Error.CONFLICT);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_ACCEPTABLE, GodotMessage.Error.UNACCEPTABLE);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();// w  w w.j a  v a  2s . c om

}

From source file:org.fao.geonet.utils.GeonetHttpRequestFactoryTest.java

@Test
public void testFollowsRedirects() throws Exception {
    final int port = 29484;
    InetSocketAddress address = new InetSocketAddress(port);
    HttpServer httpServer = HttpServer.create(address, 0);

    final Element expectedResponse = new Element("resource").addContent(new Element("id").setText("test"));
    HttpHandler finalHandler = new HttpHandler() {

        @Override/* w  w w.  j a  v a 2  s.  c  o m*/
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = Xml.getString(expectedResponse).getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    final String finalUrlPath = "/final.xml";
    httpServer.createContext(finalUrlPath, finalHandler);

    HttpHandler permRedirectHandler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = finalUrlPath.getBytes();
            exchange.getResponseHeaders().add("location", finalUrlPath);
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_PERM, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    final String permUrlPath = "/permRedirect.xml";
    httpServer.createContext(permUrlPath, permRedirectHandler);

    HttpHandler tempRedirectHandler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = finalUrlPath.getBytes();
            exchange.getResponseHeaders().add("location", finalUrlPath);
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_TEMP, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    final String tempUrlPath = "/tempRedirect.xml";
    httpServer.createContext(tempUrlPath, tempRedirectHandler);

    try {
        httpServer.start();
        XmlRequest xmlRequest = new GeonetHttpRequestFactory()
                .createXmlRequest(new URL("http://localhost:" + port + permUrlPath));
        Element response = xmlRequest.execute();
        assertEquals(Xml.getString(expectedResponse), Xml.getString(response));

        xmlRequest = new GeonetHttpRequestFactory()
                .createXmlRequest(new URL("http://localhost:" + port + tempUrlPath));
        response = xmlRequest.execute();
        assertEquals(Xml.getString(expectedResponse), Xml.getString(response));
    } finally {
        httpServer.stop(0);
    }
}

From source file:org.herrlado.websms.connector.mycoolsms.Connector.java

/**
 * Send data./*from   w  w w.  j av a  2s .c om*/
 * 
 * @param context
 *            {@link Context}
 * @param command
 *            {@link ConnectorCommand}
 * @throws WebSMSException
 *             WebSMSException
 */
private JSONObject sendData(ConnectorContext ctx, JSONObject obj) throws WebSMSException {
    // do IO

    try { // get Connection
          // send data
        HttpOptions options = new HttpOptions("utf-8");
        options.url = API_URL_BASE;
        options.addJson(obj);
        options.userAgent = API_USER_AGENT;
        options.trustAll = true;
        HttpResponse response = Utils.getHttpClient(options);
        // API_URL_BASE.toString(), null, obj, API_USER_AGENT, null,
        // "utf-8", true);
        int resp = response.getStatusLine().getStatusCode();
        if (resp != HttpURLConnection.HTTP_OK) {
            throw new WebSMSException(ctx.context, R.string.error_http, "" + resp);
        }
        String jsonText = Utils.stream2str(response.getEntity().getContent()).trim();
        if (jsonText == null || jsonText.length() == 0) {
            throw new WebSMSException(ctx.context, R.string.error_service);
        }
        // Log.d(TAG, "--HTTP RESPONSE--");
        // Log.d(TAG, jsonText);
        // Log.d(TAG, "--HTTP RESPONSE--");
        JSONObject r = new JSONObject(jsonText);
        return r;
    } catch (Exception e) {
        Log.e(TAG, null, e);
        throw new WebSMSException(e.getMessage());
    }
}

From source file:com.example.trafficvolation_android.VolationWebView.java

public String SearchRequest(String searchString) throws MalformedURLException, IOException {
    String newFeed = serverAddress + searchString;
    StringBuilder response = new StringBuilder();
    Log.v("gsearch", "url:" + newFeed);
    URL url = new URL(newFeed);
    HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();

    if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()), 8129);
        String strLine = null;/*w ww . ja v a2s  .  com*/
        while ((strLine = input.readLine()) != null) {
            response.append(strLine);
        }
        input.close();
    }

    return response.toString();
}

From source file:org.apache.hive.service.server.TestHS2HttpServerPam.java

@Test
public void testAuthorizedConnection() throws Exception {
    CloseableHttpClient httpclient = null;
    try {//from w w  w  . j a  v  a  2  s .c  o m
        String username = "user1";
        String password = "1";
        httpclient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet("http://" + host + ":" + webUIPort);
        String authB64Code = B64Code.encode(username + ":" + password, StringUtil.__ISO_8859_1);
        httpGet.setHeader(HttpHeader.AUTHORIZATION.asString(), "Basic " + authB64Code);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        Assert.assertTrue(response.toString().contains(Integer.toString(HttpURLConnection.HTTP_OK)));

    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:be.fedict.trust.ocsp.OnlineOcspRepository.java

private OCSPResp getOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate)
        throws OCSPException, IOException {
    LOG.debug("OCSP URI: " + ocspUri);
    OCSPReqGenerator ocspReqGenerator = new OCSPReqGenerator();
    CertificateID certId = new CertificateID(CertificateID.HASH_SHA1, issuerCertificate,
            certificate.getSerialNumber());
    ocspReqGenerator.addRequest(certId);
    OCSPReq ocspReq = ocspReqGenerator.generate();
    byte[] ocspReqData = ocspReq.getEncoded();

    PostMethod postMethod = new PostMethod(ocspUri.toString());
    RequestEntity requestEntity = new ByteArrayRequestEntity(ocspReqData, "application/ocsp-request");
    postMethod.addRequestHeader("User-Agent", "jTrust OCSP Client");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }//  ww w . j  av a 2 s  .c  o m
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }

    int responseCode;
    try {
        httpClient.executeMethod(postMethod);
        responseCode = postMethod.getStatusCode();
    } catch (ConnectException e) {
        LOG.debug("OCSP responder is down");
        return null;
    }

    if (HttpURLConnection.HTTP_OK != responseCode) {
        LOG.error("HTTP response code: " + responseCode);
        return null;
    }

    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        LOG.debug("no Content-Type response header");
        return null;
    }
    String resultContentType = responseContentTypeHeader.getValue();
    if (!"application/ocsp-response".equals(resultContentType)) {
        LOG.debug("result content type not application/ocsp-response");
        return null;
    }

    Header responseContentLengthHeader = postMethod.getResponseHeader("Content-Length");
    if (null != responseContentLengthHeader) {
        String resultContentLength = responseContentLengthHeader.getValue();
        if ("0".equals(resultContentLength)) {
            LOG.debug("no content returned");
            return null;
        }
    }

    OCSPResp ocspResp = new OCSPResp(postMethod.getResponseBodyAsStream());
    LOG.debug("OCSP response size: " + ocspResp.getEncoded().length + " bytes");
    return ocspResp;
}