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:edu.stanford.epadd.launcher.Main.java

private static boolean killRunningServer(String url) throws IOException {
    try {//from www .j  a  va 2 s .  co  m
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false
        String http = url
                + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection
        System.err.println("Sending a kill request to " + http);
        HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection();
        u.connect();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:com.amazon.pay.impl.Util.java

/**
 * This method uses HttpURLConnection instance to make requests.
 *
 * @param method The HTTP method (GET,POST,PUT,etc.).
 * @param url The URL/*from   w w w .j a  va  2 s. c  o  m*/
 * @param urlParameters URL Parameters
 * @param headers Header key-value pairs
 * @return ResponseData
 * @throws IOException
 */
public static ResponseData httpSendRequest(String method, String url, String urlParameters,
        Map<String, String> headers) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    if (headers != null && !headers.isEmpty()) {
        for (String key : headers.keySet()) {
            con.setRequestProperty(key, headers.get(key));
        }
    }
    con.setDoOutput(true);
    con.setRequestMethod(method);
    if (urlParameters != null) {
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }
    int responseCode = con.getResponseCode();

    BufferedReader in;
    if (responseCode != 200) {
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    } else {
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine).append(LINE_SEPARATOR);
    }
    in.close();
    return new ResponseData(responseCode, response.toString());
}

From source file:vocab.VocabUtils.java

/**
 * Jena fails to load models in https with content negotiation. Therefore I do
 * the negotiation here directly//from  w  ww. j  av a  2 s  .com
 */
private static void doContentNegotiation(OntModel model, Vocabulary v, String accept, String serialization) {
    try {
        model.read(v.getUri(), null, serialization);

    } catch (Exception e) {
        try {
            System.out.println("Failed to read the ontology. Doing content negotiation");
            URL url = new URL(v.getUri());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", accept);

            int status = connection.getResponseCode();
            if (status == HttpURLConnection.HTTP_SEE_OTHER || status == HttpURLConnection.HTTP_MOVED_TEMP
                    || status == HttpURLConnection.HTTP_MOVED_PERM) {
                String newUrl = connection.getHeaderField("Location");
                //v.setUri(newUrl);
                connection = (HttpURLConnection) new URL(newUrl).openConnection();
                connection.setRequestProperty("Accept", accept);
                InputStream in = (InputStream) connection.getInputStream();
                model.read(in, null, serialization);
            }
        } catch (Exception e2) {
            System.out.println("Failed to read the ontology");
        }
    }
}

From source file:com.talk.demo.util.NetworkUtilities.java

public static String authenticate(String username, String password) {
    String authToken = null;//  w w w .j  a  v a  2 s . c om
    String csrfToken2 = null;
    try {
        HttpURLConnection conn = HttpRequest.get(AUTH_URI).getConnection();
        //ToDo: cookie header may be null, should fix it.
        List<String> temp = conn.getHeaderFields().get("Set-Cookie");
        String cookieHeader = null;
        String csrfToken = null;
        if (null != temp && !temp.isEmpty()) {
            cookieHeader = temp.get(0);

            Log.d(TAG, "cookie: " + cookieHeader);

            csrfToken = cookieHeader.split(";")[0];
            Log.d(TAG, "csrf token : " + csrfToken);
        }

        HttpRequest request = HttpRequest.post(AUTH_URI);
        String name = username;
        String passwd = password;
        Map<String, String> data = new HashMap<String, String>();
        data.put("username", name);
        data.put("password", passwd);
        if (csrfToken != null)
            data.put("csrfmiddlewaretoken", csrfToken.substring(10));
        Log.d(TAG, "name: " + username + " passwd: " + password);
        // X-CSRFToken
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "text/html");
        if (csrfToken != null)
            headers.put("Cookie", csrfToken);

        request.headers(headers);
        request.followRedirects(false);
        HttpRequest conn4Session = request.form(data);
        conn4Session.code();
        HttpURLConnection sessionConnection = conn4Session.getConnection();
        try {
            int result = sessionConnection.getResponseCode();
            Log.e(TAG, "get response code : " + result);
            List<String> responseList = sessionConnection.getHeaderFields().get("Set-Cookie");

            if (null != responseList) {
                for (String resItem : responseList) {
                    Log.d(TAG, "cookie session: " + resItem);
                    if (resItem.contains("sessionid")) {
                        authToken = resItem.split(";")[0];
                        Log.d(TAG, "session :" + authToken);
                        NetData.setSessionId(authToken);
                    }

                    if (resItem.contains("csrftoken")) {
                        csrfToken2 = resItem.split(";")[0];
                        Log.d(TAG, "csrf token :" + csrfToken2);
                        NetData.setCsrfToken(csrfToken2);
                    }

                }
            }

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

    } catch (HttpRequestException exception) {
        Log.d(TAG, "exception : " + exception.toString());
        return null;
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }

    if ((authToken != null) && (authToken.length() > 0)) {
        Log.v(TAG, "Successful authentication");
        return authToken + ";" + csrfToken2;
    } else {
        Log.e(TAG, "Error authenticating");
        return null;
    }

}

From source file:com.depas.utils.FileUtils.java

public static boolean fileExistByURL(String urlName) {
    try {//w w w . j  av a  2s  .  co m
        HttpURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        HttpURLConnection con = (HttpURLConnection) new URL(urlName).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        logger.warn("Error checking if a file exists by URL [URLName=" + urlName + "]: " + e, e);
        return false;
    }
}

From source file:de.minestar.minestarlibrary.utils.PlayerUtils.java

private static String sendHTTPGetRequest(String URL) {
    try {/*from  www.ja  va  2 s  .c o m*/
        URL urlObject = new URL(URL);
        HttpURLConnection httpConnection = (HttpURLConnection) urlObject.openConnection();

        // optional default is GET
        httpConnection.setRequestMethod("GET");

        // add request header
        httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = httpConnection.getResponseCode();

        // the responseCode must be 200, otherwise the answer is incorrect
        // (i.e. 204 for noContent)
        if (responseCode == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            // read response
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // return response as String
            return response.toString();
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.rimbit.android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;//  ww w.j  a  v a  2 s  . c o  m

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, RIMBIT_EXPLORER_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + RIMBIT_EXPLORER_URL, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

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

    return null;

}

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

public static Schedule getSchedule(String userID) throws JsonParseException, JsonMappingException, IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Schedule").appendPath(userID).build().toString();
    // establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);/*from  w w w  .j  a  v  a  2  s.c o  m*/

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

    Schedule sched = parseSchedule(MAPPER.readTree(response));

    conn.disconnect();
    return sched;
}

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

public static User getUserInfo(String userID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(userID).build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from w  w  w .j  a  v  a2s .  com

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    JsonNode userNode = MAPPER.readTree(response);

    User ret = parseUser(userNode);
    ret.setID(userID);
    return ret;
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

public static String downloadFileAsString(String url) {
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {/*w w  w  .j  a v a  2 s.  com*/
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = bufferedReader.readLine()) != null)
                stringBuilder.append(line);

            bufferedReader.close();

            return stringBuilder.toString();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}