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.ms.tomcat.manager.TomcatManagerUrl.java

public static String appelUrl(final URL url, final String username, final String password,
        final String charset) {

    try {//from ww  w . ja  v  a  2  s .  c o  m
        final URLConnection urlTomcatConnection = url.openConnection();

        final HttpURLConnection connection = (HttpURLConnection) urlTomcatConnection;

        LOG.debug("url : " + url);
        connection.setAllowUserInteraction(false);
        connection.setDoInput(true);
        connection.setUseCaches(false);

        connection.setDoOutput(false);
        connection.setRequestMethod("GET");

        connection.setRequestProperty("Authorization", toAuthorization(username, password));

        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new TomcatManagerException("Reponse http : " + connection.getResponseMessage()
                        + " - Les droits \"manager\" ne sont pas appliques - utilisateur : \"" + username
                        + "\" password : \"" + password + "\"");
            }
            throw new TomcatManagerException("HttpURLConnection.HTTP_UNAUTHORIZED");
        }

        final String response = toString(connection.getInputStream(), charset);

        LOG.debug("reponse : " + response);

        return response;
    } catch (final Exception e) {
        throw new TomcatManagerException("L'url du manager tomcat est peut etre incorrecte : \"" + url + "\"",
                e);
    }
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

public static void doDelete(String urls, String token) {
    URL url = null;//from   www  .  jav  a  2s. co  m
    try {
        url = new URL(urls);
    } catch (MalformedURLException exception) {
        exception.printStackTrace();
    }
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        if (!Global.isEmpty(token)) {
            httpURLConnection.setRequestProperty("X-Auth-Token", token);
        }
        httpURLConnection.setRequestMethod("DELETE");
        logger.info("#####====" + httpURLConnection.getResponseCode());
    } catch (IOException e) {
        logger.error("Exception", e);
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer16(String hash) throws IOException {
    URL url;//  www  .j  a v  a2 s.  co m
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer16 + "user=" + username + "&sessionId=" + accessToken + "&serverId=" + hash;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.connect();

    if (con.getResponseCode() != 200) {
        throw new IOException("Auth server rejected username and password");
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (!"OK".equals(reply)) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java

/**
 * Validates the status of an <code>HttpURLConnection</code> against an expected HTTP
 * status code. If the current status code is not the expected one it throws an exception
 * with a detail message using Server side error messages if available.
 *
 * @param conn the <code>HttpURLConnection</code>.
 * @param expected the expected HTTP status code.
 * @throws IOException thrown if the current status code does not match the expected one.
 *//*ww w  .j ava 2 s.  com*/
private static void validateResponse(HttpURLConnection conn, int expected) throws IOException {
    int status = conn.getResponseCode();
    if (status != expected) {
        try {
            JSONObject json = (JSONObject) jsonParse(conn);
            throw new IOException(MessageFormat.format("HTTP status [{0}], {1} - {2}", json.get("status"),
                    json.get("reason"), json.get("message")));
        } catch (IOException ex) {
            if (ex.getCause() instanceof IOException) {
                throw (IOException) ex.getCause();
            }
            throw new IOException(
                    MessageFormat.format("HTTP status [{0}], {1}", status, conn.getResponseMessage()));
        }
    }
}

From source file:es.tid.cep.esperanza.Utils.java

public static boolean DoHTTPPost(String urlStr, String content) {
    try {//ww w . j a  v a2  s .  c o  m
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.debug("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me.getMessage());
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe.getMessage());
        return false;
    }
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
    String charset = getResponseCharset(conn.getContentType());
    InputStream es = conn.getErrorStream();
    if (es == null) {
        return getStreamAsString(conn.getInputStream(), charset);
    } else {/*w  w w .j a v a 2 s  .  c o m*/
        String msg = getStreamAsString(es, charset);
        if (StringUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else {
            throw new IOException(msg);
        }
    }
}

From source file:eu.eubrazilcc.lvl.oauth2.AuthTest.java

private static HttpURLConnection doRequest(final OAuthClientRequest request) throws IOException {
    final URL url = new URL(request.getLocationUri());
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(true);
    conn.connect();//from   w ww . ja v a2 s.  c o  m
    conn.getResponseCode();
    return conn;
}

From source file:Authentication.DinserverAuth.java

public static boolean Login(String nick, String pass, Socket socket) throws IOException {
    boolean logged = false;

    JSONObject authRequest = new JSONObject();
    authRequest.put("username", nick);
    authRequest.put("auth_id", pass);

    String query = "http://127.0.0.1:5000/token";

    URL url = new URL(query);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);//from  ww  w. ja v a  2s  .  c  om
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");

    OutputStream os = conn.getOutputStream();
    os.write(authRequest.toString().getBytes(Charset.forName("UTF-8")));
    os.close();
    String output = new String();
    StringBuilder sb = new StringBuilder();
    int HttpResult = conn.getResponseCode();
    if (HttpResult == HttpURLConnection.HTTP_OK) {
        output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
    } else {
        System.out.println(conn.getResponseMessage());
    }

    JSONObject jsonObject = new JSONObject(output);
    logged = jsonObject.getBoolean("ok");

    conn.disconnect();

    if (logged) {
        if (DinserverMaster.addUser(nick, socket)) {
            System.out.println("User " + nick + " logged in");
        } else {
            logged = false;
        }
    }
    return logged;
}

From source file:localSPs.SpiderOakAPI.java

public static String connectWithREST(String url, String method)
        throws IOException, ProtocolException, MalformedURLException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);//  w  ww. java2s  . c o  m
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT))
        con.addRequestProperty("Authorization", "Base M5XWW5JNONZWUMSANBXXI3LBNFWC4Y3PNU5E2NDSNFXTEMZVJ5QWW");

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();
    return newURL;
}

From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java

private static String getCookie(String authToken) throws IOException {
    HttpURLConnection connection = null;
    try {//from  w ww  .  java 2 s.co  m
        connection = (HttpURLConnection) new URL(
                BuildConfig.HOST + "/_ah/login?continue=http://localhost/&auth=" + authToken).openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.connect();
        if (connection.getResponseCode() != 302) {
            Log.e(TAG, "Cannot fetch the cookie: " + connection.getResponseCode());
            return null;
        }
        String cookie = connection.getHeaderField("Set-Cookie");
        if (!cookie.contains("SACSID")) {
            return null;
        }
        return cookie;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}