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.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java

public boolean URLExists(String url) {
    try {/*from   ww w  .ja v a  2 s  .  com*/
        HttpURLConnection.setFollowRedirects(true);
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception ex) {
        Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, url + "\n" + ex);
        return false;
    }

}

From source file:com.telefonica.iot.perseo.UtilsTest.java

/**
 * Test of DoHTTPPost method, of class Utils.
 *//* ww  w.  ja va 2s .  c o m*/
@Test
public void testDoHTTPPost() {
    System.out.println("DoHTTPPost");
    InetSocketAddress address = new InetSocketAddress(Help.PORT);
    HttpServer httpServer = null;
    try {
        httpServer = HttpServer.create(address, 0);
        HttpHandler handler = new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                byte[] response = "OK\n".getBytes();
                exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
                exchange.getResponseBody().write(response);
                exchange.close();
            }
        };
        httpServer.createContext("/path", handler);
        httpServer.start();
        boolean result = Utils.DoHTTPPost(String.format("http://localhost:%d/path", Help.PORT), "xxxxx");
        assertEquals(true, result);
        result = Utils.DoHTTPPost(String.format("http://localhost:%d/notexist", Help.PORT), "xxxxx");
        assertEquals(false, result);
        result = Utils.DoHTTPPost("<<this is an invalid URL>>", "xxxxx");
        assertEquals(false, result);

    } catch (IOException ex) {
        Logger.getLogger(UtilsTest.class.getName()).log(Level.SEVERE, null, ex);
        fail(ex.toString());
    } finally {
        if (httpServer != null) {
            httpServer.stop(0);
        }
    }

}

From source file:i5.las2peer.services.todolist.Todolist.java

/**
 * //from w w  w . j  av  a2 s  .  co m
 * deleteData
 * 
 * 
 * @return HttpResponse
 * 
 */
@DELETE
@Path("/data/{id}")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "responseDeleteData") })
@ApiOperation(value = "deleteData", notes = "")
public HttpResponse deleteData(@PathParam("id") Integer id) {
    Connection conn = null;
    try {

        conn = dbm.getConnection();
        PreparedStatement stmt = conn.prepareStatement("DELETE FROM gamificationCAE.todolist WHERE id = ?");
        stmt.setInt(1, id);
        stmt.executeUpdate();
        stmt = conn.prepareStatement("ALTER TABLE todolist AUTO_INCREMENT = 1;");
        stmt.executeUpdate();
        return new HttpResponse("data number " + id + " is deleted!", HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

        return new HttpResponse("Database connection error", HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.openremote.android.test.console.net.ORNetworkCheckTest.java

/**
 * Connect to controller.openremote.org/test/controller instance and attempt to verify a
 * panel design ID that has white space in the name.
 *
 * @throws IOException if remote test controller can't be accessed
 *///from  w  w  w.jav a2  s.c o m
public void testVerifyControllerURLSpacesInPanelName() throws IOException {
    try {
        AppSettingsModel.setCurrentPanelIdentity(ctx, "Name With Spaces");

        //if (!wifi.isWifiEnabled())
        //  fail(wifiRequired());

        HttpResponse response = ORNetworkCheck.verifyControllerURL(ctx,
                "http://controller.openremote.org/test/controller");

        assertNotNull("Got null response, was expecting " + HttpURLConnection.HTTP_OK, response);

        int status = response.getStatusLine().getStatusCode();

        assertTrue("Was expecting " + HttpURLConnection.HTTP_OK + " response, got : " + status,
                status == HttpURLConnection.HTTP_OK);
    } finally {
        AppSettingsModel.setCurrentPanelIdentity(ctx, null);
    }
}

From source file:com.datos.vfs.provider.http.HttpFileObject.java

/**
 * Determines the type of this file.  Must not return null.  The return
 * value of this method is cached, so the implementation can be expensive.
 *//*w w w.  jav a2s. c o  m*/
@Override
protected FileType doGetType() throws Exception {
    // Use the HEAD method to probe the file.
    final int status = this.getHeadMethod().getStatusCode();
    if (status == HttpURLConnection.HTTP_OK
            || status == HttpURLConnection.HTTP_BAD_METHOD /* method is bad, but resource exist */) {
        return FileType.FILE;
    } else if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) {
        return FileType.IMAGINARY;
    } else {
        throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status));
    }
}

From source file:i5.las2peer.services.servicePackage.TemplateService.java

/**
 * Example method that returns a phrase containing the received input.
 * /*from   ww  w .j av a2  s. c om*/
 * @param myInput
 * 
 */
@POST
@Path("/myResourcePath/{input}")
@Produces(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Input Phrase"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Sample Resource", notes = "Example method that returns a phrase containing the received input.")
public HttpResponse exampleMethod(@PathParam("input") String myInput) {
    String returnString = "";
    returnString += "You have entered " + myInput + "!";

    return new HttpResponse(returnString, HttpURLConnection.HTTP_OK);
}

From source file:com.shuffle.bitcoin.blockchain.Btcd.java

/**
 * This method will take in an address hash and return a List of all transactions associated with
 * this address.  These transactions are in bitcoinj's Transaction format.
 *///from   w ww  .j  a v a 2 s  .  c  o  m
public synchronized List<Transaction> getAddressTransactionsInner(String address) throws IOException {

    List<Transaction> txList = null;
    String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"searchrawtransactions\", \"params\":[\""
            + address + "\"]}";

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "application/json");
    Base64 b = new Base64();
    String authString = rpcuser + ":" + rpcpass;
    String encoding = b.encodeAsString(authString.getBytes());
    connection.setRequestProperty("Authorization", "Basic " + encoding);
    connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length));
    connection.setDoInput(true);
    OutputStream out = connection.getOutputStream();
    out.write(requestBody.getBytes());

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        JSONObject json = new JSONObject(response.toString());
        JSONArray jsonarray = null;
        txList = new LinkedList<>();
        if (json.isNull("result")) {
            return txList;
        } else {
            jsonarray = json.getJSONArray("result");
        }
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject currentJson = jsonarray.getJSONObject(i);
            String txid = currentJson.get("txid").toString();
            HexBinaryAdapter adapter = new HexBinaryAdapter();
            byte[] bytearray = adapter.unmarshal(currentJson.get("hex").toString());
            Context context = Context.getOrCreate(netParams);
            int confirmations = Integer.parseInt(currentJson.get("confirmations").toString());
            boolean confirmed;
            if (confirmations == 0) {
                confirmed = false;
            } else {
                confirmed = true;
            }
            org.bitcoinj.core.Transaction bitTx = new org.bitcoinj.core.Transaction(netParams, bytearray);
            Transaction tx = new Transaction(txid, bitTx, false, confirmed);
            txList.add(tx);
        }

    }

    out.flush();
    out.close();

    return txList;

}

From source file:net.kervala.comicsreader.BrowseRemoteAlbumsTask.java

@Override
protected String doInBackground(String... params) {
    String error = null;/*from   w  ww .  j  a v a  2s.  c om*/

    URL url = null;

    try {
        // open a stream on URL
        url = new URL(mUrl);
    } catch (MalformedURLException e) {
        error = e.toString();
        e.printStackTrace();
    }

    boolean retry = false;
    HttpURLConnection urlConnection = null;
    int resCode = 0;

    do {
        // create the new connection
        ComicsAuthenticator.sInstance.reset();

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

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(ComicsParameters.TIME_OUT);
            urlConnection.setReadTimeout(ComicsParameters.TIME_OUT);
            resCode = urlConnection.getResponseCode();
        } catch (EOFException e) {
            // under Android 4
            resCode = -1;
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("ComicsReader", "Rescode " + resCode);

        if (resCode < 0) {
            retry = true;
        } else if (resCode == 401) {
            ComicsAuthenticator.sInstance.setResult(false);

            // user pressed cancel
            if (!ComicsAuthenticator.sInstance.isValidated()) {
                return null;
            }

            retry = true;
        } else {
            retry = false;
        }
    } while (retry);

    if (resCode != HttpURLConnection.HTTP_OK) {
        ComicsAuthenticator.sInstance.setResult(false);

        // TODO: HTTP error occurred 
        return null;
    }

    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    InputStream is = null;

    try {
        // download the file
        is = new BufferedInputStream(urlConnection.getInputStream(), ComicsParameters.BUFFER_SIZE);

        int count = 0;
        byte data[] = new byte[ComicsParameters.BUFFER_SIZE];

        while ((count = is.read(data)) != -1) {
            bytes.write(data, 0, count);
        }

        ComicsAuthenticator.sInstance.setResult(true);
    } catch (IOException e) {
        error = e.toString();
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

    if (bytes != null) {
        final String text = new String(bytes.toByteArray());

        if (text.contains("<albums>")) {
            parseXml(text);
        } else if (text.contains("\"albums\":")) {
            parseJson(text);
        } else {
            Log.e("ComicsReader", "Error");
        }
    }

    return error;
}

From source file:it.infn.ct.indigo.futuregateway.server.FGServerManager.java

/**
 * Add a new resource into the FG service.
 *
 * @param companyId The id of the instance
 * @param collection The name of the collection to post the new resource
 * @param resourceId The id of the resource to add. If provided the
 *                   resource will be overwritten
 * @param resource The resource information in JSON format
 * @param token The token of the user performing the action
 * @return The Id of the new resource/*w ww  . j av a2s .  c om*/
 * @throws PortalException Cannot retrieve the server endpoint
 * @throws IOException Connect communicate with the server
 */
public final String addResource(final long companyId, final String collection, final String resourceId,
        final String resource, final String token) throws PortalException, IOException {
    log.debug("Updating/adding the resource in " + collection + ": " + resource);
    HttpURLConnection connection;
    boolean resourceExist = false;

    if (resourceId != null && !resourceId.isEmpty()) {
        resourceExist = true;
        connection = getFGConnection(companyId, collection, resourceId, token, HttpMethods.PUT,
                FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE);
    } else {
        connection = getFGConnection(companyId, collection, null, token, HttpMethods.POST,
                FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE);
    }
    OutputStream os = connection.getOutputStream();
    os.write(resource.getBytes());
    os.flush();
    if (resourceExist && connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        return resourceId;
    }
    if (!resourceExist && connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new IOException("Impossible to add the resource. " + "Server response with code: "
                + connection.getResponseCode());
    }
    StringBuilder result = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        String readLine;
        while ((readLine = br.readLine()) != null) {
            result.append(readLine);
        }
    }
    connection.disconnect();
    JSONObject jRes = JSONFactoryUtil.createJSONObject(result.toString());
    return jRes.getString(FGServerConstants.ATTRIBUTE_ID);
}

From source file:com.checkmarx.jenkins.CxWebService.java

private void checkServerConnectivity(URL url) throws AbortException {
    int seconds = CxConfig.getRequestTimeOutDuration();
    int milliseconds = seconds * 1000;

    try {//from  w ww .  j av a2 s .  co m
        HttpURLConnection urlConn;
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setConnectTimeout(milliseconds);
        urlConn.setReadTimeout(milliseconds);
        urlConn.connect();
        if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new AbortException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS);
        }
    } catch (IOException e) {
        logger.debug(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS, e);
        throw new AbortException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADRESS);
    }
}