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.github.dpsm.android.print.gson.GsonResultOperator.java

@Override
public Subscriber<? super Response> call(final Subscriber<? super T> subscriber) {
    return new Subscriber<Response>() {
        @Override//from  w  w  w .ja v  a  2s. c  om
        public void onCompleted() {
            subscriber.onCompleted();
        }

        @Override
        public void onError(final Throwable e) {
            subscriber.onError(e);
        }

        @Override
        public void onNext(final Response response) {
            switch (response.getStatus()) {
            case HttpURLConnection.HTTP_OK:
                InputStreamReader reader = null;
                try {
                    reader = new InputStreamReader(response.getBody().in());
                    final JsonElement jsonElement = mGSON.fromJson(new JsonReader(reader), JsonObject.class);
                    if (jsonElement != null && jsonElement.isJsonObject()) {
                        final T result = mConstructor.newInstance(jsonElement.getAsJsonObject());
                        subscriber.onNext(result);
                    }
                } catch (Exception e) {
                    subscriber.onError(e);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            // Nothing to do here
                        }
                    }
                }
                break;
            default:
                subscriber.onError(new IOException("Http Response Failed: " + response.getStatus()));
                break;
            }
        }
    };
}

From source file:com.beginner.core.utils.SmsUtil.java

public static String SMS(String postData, String postUrl) {
    try {/*  w w  w .ja  v  a2 s.c o  m*/
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Length", "" + postData.length());
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        out.write(postData);
        out.flush();
        out.close();

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            return "";
        }
        //??
        String line, result = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while ((line = in.readLine()) != null) {
            result += line + "\n";
        }
        in.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return "";
}

From source file:de.egore911.versioning.deployer.Main.java

private static void perform(String arg, CommandLine line) throws IOException {
    URL url;//  w  w w  .j  a va2  s.  c o  m
    try {
        url = new URL(arg);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        System.exit(1);
        return;
    }

    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();
        if (response != HttpURLConnection.HTTP_OK) {
            LOG.error("Could not download {}", url);
            connection.disconnect();
            System.exit(1);
            return;
        }
    } catch (ConnectException e) {
        LOG.error("Error during download from URI {}: {}", url, e.getMessage());
        System.exit(1);
        return;
    }

    XmlHolder xmlHolder = XmlHolder.getInstance();
    DocumentBuilder documentBuilder = xmlHolder.documentBuilder;
    XPath xPath = xmlHolder.xPath;

    try {

        XPathExpression serverNameXpath = xPath.compile("/server/name/text()");
        XPathExpression serverTargetdirXpath = xPath.compile("/server/targetdir/text()");
        XPathExpression serverDeploymentsDeploymentXpath = xPath.compile("/server/deployments/deployment");

        Document doc = documentBuilder.parse(connection.getInputStream());
        connection.disconnect();

        String serverName = (String) serverNameXpath.evaluate(doc, XPathConstants.STRING);
        LOG.info("Deploying {}", serverName);

        boolean shouldPerformCopy = !line.hasOption('r');
        PerformCopy performCopy = new PerformCopy(xPath);
        boolean shouldPerformExtraction = !line.hasOption('r');
        PerformExtraction performExtraction = new PerformExtraction(xPath);
        boolean shouldPerformCheckout = !line.hasOption('r');
        PerformCheckout performCheckout = new PerformCheckout(xPath);
        boolean shouldPerformReplacement = true;
        PerformReplacement performReplacement = new PerformReplacement(xPath);

        String targetdir = (String) serverTargetdirXpath.evaluate(doc, XPathConstants.STRING);
        FileUtils.forceMkdir(new File(targetdir));

        NodeList serverDeploymentsDeploymentNodes = (NodeList) serverDeploymentsDeploymentXpath.evaluate(doc,
                XPathConstants.NODESET);
        int max = serverDeploymentsDeploymentNodes.getLength();
        for (int i = 0; i < serverDeploymentsDeploymentNodes.getLength(); i++) {
            Node serverDeploymentsDeploymentNode = serverDeploymentsDeploymentNodes.item(i);

            // Copy
            if (shouldPerformCopy) {
                performCopy.perform(serverDeploymentsDeploymentNode);
            }

            // Extraction
            if (shouldPerformExtraction) {
                performExtraction.perform(serverDeploymentsDeploymentNode);
            }

            // Checkout
            if (shouldPerformCheckout) {
                performCheckout.perform(serverDeploymentsDeploymentNode);
            }

            // Replacement
            if (shouldPerformReplacement) {
                performReplacement.perform(serverDeploymentsDeploymentNode);
            }

            logPercent(i + 1, max);
        }

        // validate that "${versioning:" is not present
        Collection<File> files = FileUtils.listFiles(new File(targetdir), TrueFileFilter.TRUE,
                TrueFileFilter.INSTANCE);
        for (File file : files) {
            String content;
            try {
                content = FileUtils.readFileToString(file);
            } catch (IOException e) {
                continue;
            }
            if (content.contains("${versioning:")) {
                LOG.error("{} contains placeholders even after applying the replacements",
                        file.getAbsolutePath());
            }
        }

        LOG.info("Done deploying {}", serverName);

    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Error performing deployment: {}", e.getMessage(), e);
    }
}

From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java

/**
 * HEAD methods return an empty response body. If a HEAD request populates
 * a cache and then a GET follorws, a blank page will result.
 * This test ensures that the SimplePageCachingFilter implements calculateKey
 * properly to avoid this problem./*from w ww  . ja v a 2 s.  c o  m*/
 */
public void testHeadThenGetOnCachedPage() throws Exception {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new HeadMethod(buildUrl(cachedPageUrl));
    int responseCode = httpClient.executeMethod(httpMethod);
    //httpclient follows redirects, so gets the home page.
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));

    httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    responseCode = httpClient.executeMethod(httpMethod);
    responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);

}

From source file:org.jboss.additional.testsuite.jdkall.present.ejb.sfsb.SfsbTestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)/*from  www.ja  va  2s  .  c  o  m*/
public void sfsbTest(@ArquillianResource URL url) throws Exception {
    URL testURL = new URL(url.toString() + "sfsbCache?product=makaronia&quantity=10");

    final HttpGet request = new HttpGet(testURL.toString());
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(request);
        Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK,
                response.getStatusLine().getStatusCode());
        Thread.sleep(1000);
        response = httpClient.execute(request);
        Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK,
                response.getStatusLine().getStatusCode());
    } finally {
        IOUtils.closeQuietly(response);
        httpClient.close();
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Delete specified dataset// ww  w.j a va2  s. c om
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void deleteDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("delete dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets/" + dataSetName);
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("DELETE");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:foam.blob.RestBlobService.java

@Override
public Blob find_(X x, Object id) {
    InputStream is = null;//from w  w w  .j a va 2  s  .c  o m
    ByteArrayOutputStream os = null;
    HttpURLConnection connection = null;

    try {
        URL url = new URL(this.address_ + "/" + id.toString());
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK || connection.getContentLength() == -1) {
            throw new RuntimeException("Failed to find blob");
        }

        is = new BufferedInputStream(connection.getInputStream());
        os = new ByteArrayOutputStream();

        int read = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((read = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
            os.write(buffer, 0, read);
        }

        return new ByteArrayBlob(os.toByteArray());
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
        IOUtils.close(connection);
    }
}

From source file:nz.skytv.example.SwaggerApplication.java

@RequestMapping(value = { "/rest/books" }, method = RequestMethod.GET)
@ApiOperation(value = "Retrieve the list of books", notes = "Retrieve books.", response = Book.class, tags = {
        "book", "searches" })
@ApiResponses({ @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Books retrieved successfully"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Something really bad happened") })
List<Book> findBooksByIsbn(final String isbn) {
    LOG.debug("findBy {}", isbn);
    return Arrays.asList(new Book());
}

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

@Test
public void testStackServlet() throws Exception {
    String baseURL = "http://localhost:" + webUIPort + "/stacks";
    URL url = new URL(baseURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    boolean contents = false;
    String line;//from ww  w .j av  a 2  s.  c  om
    while ((line = reader.readLine()) != null) {
        if (line.contains("Process Thread Dump:")) {
            contents = true;
        }
    }
    Assert.assertTrue(contents);
}

From source file:com.thomaskuenneth.openweathermapweather.WeatherUtils.java

public static String getFromServer(String url) throws MalformedURLException, IOException {
    StringBuilder sb = new StringBuilder();
    URL _url = new URL(url);
    HttpURLConnection httpURLConnection = (HttpURLConnection) _url.openConnection();
    String contentType = httpURLConnection.getContentType();
    String charSet = "ISO-8859-1";
    if (contentType != null) {
        Matcher m = PATTERN_CHARSET.matcher(contentType);
        if (m.matches()) {
            charSet = m.group(1);//from   w w  w  .j  a  va2 s .  co m
        }
    }
    final int responseCode = httpURLConnection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream(),
                charSet);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, "getFromServer()", ex);
        }
    }
    httpURLConnection.disconnect();
    return sb.toString();
}