Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

In this page you can find the example usage for java.net HttpURLConnection getResponseCode.

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:fr.gael.dhus.service.ProductService.java

private static void wcsDeleteCoverage(String coverageId) throws IOException {
    String GET_URL = "http://localhost:8080/rasdaman/ows?SERVICE=WCS&VERSION=2.0.1&request=DeleteCoverage&coverageId="
            + coverageId;//  w  w w .ja  va  2s.  c o  m
    String USER_AGENT = "Mozilla/5.0";
    URL obj = new URL(GET_URL);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", USER_AGENT);
    int responseCode = con.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK)
        logger.info("Successfully deleted coverage with id " + coverageId);
    else
        logger.error("NoSuchCoverage");
}

From source file:fr.gael.dhus.service.ProductService.java

private static void wmsDeleteLayer(String coverageId) throws IOException {
    String GET_URL = "http://localhost:8080/rasdaman/ows?service=WMS&version=1.3.0&request=DeleteLayer&layer="
            + coverageId;/*from w  ww.  jav  a  2 s.  co  m*/
    String USER_AGENT = "Mozilla/5.0";
    URL obj = new URL(GET_URL);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", USER_AGENT);
    int responseCode = con.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK)
        logger.info("Successfully deleted layer with id " + coverageId);
    else
        logger.error("NoSuchLayer");
}

From source file:io.helixservice.feature.configuration.cloudconfig.CloudConfigDecrypt.java

/**
 * Decrypt an encrypted string/*w ww .j  a v a 2s  . c  om*/
 * <p>
 * This method blocks on a HTTP request.
 *
 * @param name property or filename for reference/logging
 * @param encryptedValue Encrypted string
 * @param cloudConfigUri URI of the Cloud Config server
 * @param httpBasicHeader HTTP Basic header containing username and password for Cloud Config server
 * @return
 */
public static String decrypt(String name, String encryptedValue, String cloudConfigUri,
        String httpBasicHeader) {
    String result = encryptedValue;

    // Remove prefix if needed
    if (encryptedValue.startsWith(CIPHER_PREFIX)) {
        encryptedValue = encryptedValue.substring(CIPHER_PREFIX.length());
    }

    String decryptUrl = cloudConfigUri + "/decrypt";

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(decryptUrl).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.setRequestMethod("POST");
        connection.addRequestProperty(AUTHORIZATION_HEADER, httpBasicHeader);
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Content-Length", Integer.toString(encryptedValue.getBytes().length));
        connection.setRequestProperty("Accept", "*/*");

        // Write body
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(encryptedValue.getBytes());
        outputStream.close();

        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            result = IOUtils.toString(inputStream);
            inputStream.close();
        } else {
            LOG.error("Unable to Decrypt name=" + name + " due to httpStatusCode="
                    + connection.getResponseCode() + " for decryptUrl=" + decryptUrl);
        }
    } catch (IOException e) {
        LOG.error("Unable to connect to Cloud Config server at decryptUrl=" + decryptUrl, e);
    }

    return result;
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<Task> getTasks(String userID) throws JsonParseException, JsonMappingException, IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Tasks").appendPath(userID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from ww w .jav  a2 s . c om

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    // Initialize ObjectMapper
    List<Task> taskList = new ArrayList<Task>();
    final JsonNode taskArray = MAPPER.readTree(response).get(Keys.Task.LIST);

    if (taskArray.isArray()) {
        for (final JsonNode taskNode : taskArray) {
            Task t = TaskDatabaseAdapter.parseTasks(taskNode);
            if (t != null) {
                taskList.add(t);
            }
        }
    } else {
        Log.e(TAG, "Error parsing user's task list");
    }

    conn.disconnect();
    for (Task t : taskList) {
        TaskDatabaseAdapter.getTask(t);
    }
    return taskList;
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - file on the repo in static
 * @return boolean representing if the file exists 
 *//*from   w ww .j  av a  2s . c  om*/
public static boolean staticFileExists(String file) {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(getStaticCreeperhostLink(file))
                .openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        return (connection.getResponseCode() == 200);
    } catch (Exception e) {
        return false;
    }
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<Note> getNotes(String userID) throws Exception {
    // Server URL setup
    String _url = getBaseUri().appendPath("Notes").appendPath(userID).build().toString();
    Log.d("GETNOTES", _url);
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);// w  ww.j a v a  2  s .  co m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    // Initialize ObjectMapper
    List<Note> noteList = new ArrayList<Note>();
    List<String> noteIds = new ArrayList<String>();
    final JsonNode noteArray = MAPPER.readTree(response).get(Keys.Note.LIST);

    if (noteArray.isArray()) {
        for (final JsonNode noteNode : noteArray) {
            Note n = NotesDatabaseAdapter.getNote(JsonUtils.getJSONValue(noteNode, Keys.Note.ID));
            n.setCreatedBy(JsonUtils.getJSONValue(noteNode, Keys.Note.CREATED_BY));
            if (n != null) {
                noteList.add(n);
            }
            noteIds.add(noteNode.get(Keys.Note.ID).asText());
        }
    } else {
        Log.e(TAG, "Error parsing user's notes list");
    }

    conn.disconnect();
    return noteList;
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<Group> getGroups(String userID) throws IOException {
    // Server URL setup
    System.out.println(userID);/*from  www  .j a v a 2  s  . co m*/
    String _url = getBaseUri().appendPath("Groups").appendPath(userID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    System.out.println("yes");

    // Initialize ObjectMapper
    List<Group> groupList = new ArrayList<Group>();
    List<String> groupIDList = new ArrayList<String>();
    System.out.println("maybe");
    final JsonNode groupArray = MAPPER.readTree(response).get(Keys.Group.LIST);
    System.out.println("no");

    if (groupArray.isArray()) {
        for (final JsonNode groupNode : groupArray) {
            String _id = groupNode.get(Keys.Group.ID).asText();
            System.out.println(_id);
            groupIDList.add(_id);
        }
    }
    conn.disconnect();

    for (String id : groupIDList) {
        groupList.add(GroupDatabaseAdapter.getGroup(id));
    }

    return groupList;
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Forms an HTTP request, sends it using GET method and returns the result of the request as a String.
 * //  ww w .  j  a v a 2 s.com
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    if (clientId != null && clientSecret != null && System.currentTimeMillis() > tokenExpiration) {
        String tokenJson = getToken(clientId, clientSecret);
        Integer expiresIn = Integer
                .parseInt((String) ((JSONObject) JSONValue.parse(tokenJson)).get("expires_in"));
        tokenExpiration = System.currentTimeMillis() + ((expiresIn * 1000) - 1);
        token = "Bearer " + (String) ((JSONObject) JSONValue.parse(tokenJson)).get("access_token");
    }
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", contentType + "; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    if (token != null) {
        uc.setRequestProperty("Authorization", token);
    }
    uc.setRequestMethod("GET");
    uc.setDoOutput(true);

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - file on the repo//from  ww w  .  ja v a 2  s. c  om
 * @return boolean representing if the file exists 
 */
public static boolean fileExists(String file) {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(Locations.masterRepo + "/FTB2/" + file)
                .openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        return (connection.getResponseCode() == 200);
    } catch (Exception e) {
        return false;
    }
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - the name of the file, as saved to the repo (including extension)
 * @return - the direct link//w w w .j a  v  a  2 s .  c o  m
 */
public static String getStaticCreeperhostLink(String file) {
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/FTB2/static/" + file;
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        if (connection.getResponseCode() != 200) {
            for (String server : downloadServers.values()) {
                if (connection.getResponseCode() != 200) {
                    resolved = "http://" + server + "/FTB2/static/" + file;
                    connection = (HttpURLConnection) new URL(resolved).openConnection();
                    connection.setRequestProperty("Cache-Control", "no-transform");
                    connection.setRequestMethod("HEAD");
                } else {
                    break;
                }
            }
        }
    } catch (IOException e) {
    }
    connection.disconnect();
    return resolved;
}