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:com.meetingninja.csse.database.TaskDatabaseAdapter.java

public static Boolean deleteTask(String taskID) throws IOException {
    String _url = getBaseUri().appendPath(taskID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.DELETE);
    addRequestHeader(conn, false);/* www.j a  v  a2s . co  m*/
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    boolean result = false;
    JsonNode tree = MAPPER.readTree(response);
    if (!response.isEmpty()) {
        if (!tree.has(Keys.DELETED)) {
            result = true;
        } else {
            logError(TAG, tree);
        }
    }

    conn.disconnect();
    return result;

}

From source file:cc.vileda.sipgatesync.api.SipgateApi.java

@NonNull
private static String getUrl(final String apiUrl, final String token) throws IOException {
    final HttpURLConnection urlConnection = getConnection(apiUrl);
    urlConnection.setDoInput(true);/*from w ww .  j  a  v a  2 s  . com*/
    urlConnection.setRequestMethod("GET");
    if (token != null) {
        urlConnection.setRequestProperty("Authorization", "Bearer " + token);
    }
    StringBuilder sb = new StringBuilder();
    int HttpResult = urlConnection.getResponseCode();
    if (HttpResult == HttpURLConnection.HTTP_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();

        return sb.toString();
    } else {
        System.out.println(urlConnection.getResponseMessage());
    }

    return "";
}

From source file:Main.java

/**
 * Return '' or error message if error occurs during URL connection.
 * //from w  w w .  j a  va  2s .  c  o m
 * @param url   The URL to ckeck
 * @return
 */
public static String getUrlStatus(String url) {
    URL u;
    URLConnection conn;
    int connectionTimeout = 500;
    try {
        u = new URL(url);
        conn = u.openConnection();
        conn.setConnectTimeout(connectionTimeout);

        // TODO : set proxy

        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) conn;
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.connect();
            httpConnection.disconnect();
            // FIXME : some URL return HTTP200 with an empty reply from server 
            // which trigger SocketException unexpected end of file from server
            int code = httpConnection.getResponseCode();

            if (code == HttpURLConnection.HTTP_OK) {
                return "";
            } else {
                return "Status: " + code;
            }
        } // TODO : Other type of URLConnection
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }

    return "";
}

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

public static Meeting getMeetingInfo(String meetingID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(meetingID).build().toString();

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

    // add request header
    conn.setRequestMethod("GET");
    addRequestHeader(conn, false);//from  ww  w .j a  va  2s. c  o m

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

    Meeting ret = parseMeeting(meetingNode);
    ret.setID(meetingID);
    return ret;
}

From source file:core.Utility.java

public static ArrayList<String> getWikiText(String _word) throws MalformedURLException, IOException {
    ArrayList<String> _list = new ArrayList();
    try {//from w w  w .  ja v  a 2  s  .co  m

        URL url = new URL("http://en.wiktionary.org/w/api.php" + "?action=parse" + "&prop=wikitext" + "&page="
                + _word + "&format=xmlfm");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output, wikiText = "";
        while ((output = br.readLine()) != null) {
            wikiText += output + "\n";
        }

        conn.disconnect();

    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return _list;
}

From source file:com.mytwitter.Network.NetworkHelper.java

/**
 * Verifies that the handset is connected to the Internet.
 *
 * @return//from   w w  w .  j ava2s. c o  m
 */
public static boolean connectedToInternet(Context context) throws IOException {

    if (!connectedToNetwork(getConnectivityManager(context)))
        return false;

    URL googleUrl = new URL(WEBADDRESS_GOOGLE_COM_URL);
    HttpURLConnection connection = (HttpURLConnection) googleUrl.openConnection();
    connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT);
    connection.connect();

    if (connection.getResponseCode() == HttpStatus.SC_OK)
        return true;

    return false;

    /**
     *  Alternative way (NOT TESTED):
     *
     boolean result = false;
            
     URL url;
     HttpURLConnection connection = null;
            
     try {
     url = new URL(WEBADDRESS_ANDROID_COM_URL);
            
     connection = (HttpURLConnection) url.openConnection();
     connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT);
     connection.setReadTimeout(NETWORK_CONNECTION_READ_TIMEOUT);
            
     InetAddress address = InetAddress.getByName(WEBADDRESS_ANDROID_COM_IP);
            
     result = address.isReachable(NETWORK_CONNECTION_CONNECT_TIMEOUT);
            
     // Redirect check is valid only after the response headers have been received
     // InputStream in = new BufferedInputStream(connection.getInputStream());
            
     //            if (url.getHost().equals(connection.getURL().getHost()))
     //                result = true;
            
     } catch (Exception e) {
     e.printStackTrace();
     } finally {
     connection.disconnect();
     }
            
     return result;
     */
}

From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java

/**
 * Reads the response as a JSON object.//from ww  w  .j  ava2  s.co  m
 *
 * @param connection The connection.
 *
 * @return An object returned by the GSON's {@link JSONParser#parse(Reader)}.
 * @throws IOException    If an exception occurred while contacting the server.
 * @throws ParseException If the response cannot be parsed as a JSON object.
 */
private static Object readResponse(HttpURLConnection connection) throws IOException, ParseException {
    if (connection.getResponseCode() == 204)
        return null;

    return new JSONParser().parse(new InputStreamReader(connection.getInputStream()));
}

From source file:hudson.Main.java

/**
 * Run command and send result to {@code ExternalJob} in the {@code external-monitor-job} plugin.
 * Obsoleted by {@code SetExternalBuildResultCommand} but kept here for compatibility.
 *///from   w w  w . ja v a 2  s  .co  m
public static int remotePost(String[] args) throws Exception {
    String projectName = args[0];

    String home = getHudsonHome();
    if (!home.endsWith("/"))
        home = home + '/'; // make sure it ends with '/'

    // check for authentication info
    String auth = new URL(home).getUserInfo();
    if (auth != null)
        auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8"));

    {// check if the home is set correctly
        HttpURLConnection con = open(new URL(home));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200 || con.getHeaderField("X-Hudson") == null) {
            System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")");
            return -1;
        }
    }

    URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");

    {// check if the job name is correct
        HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200) {
            System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " "
                    + con.getResponseMessage() + ")");
            return -1;
        }
    }

    // get a crumb to pass the csrf check
    String crumbField = null, crumbValue = null;
    try {
        HttpURLConnection con = open(
                new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
        String[] components = line.split(":");
        if (components.length == 2) {
            crumbField = components[0];
            crumbValue = components[1];
        }
    } catch (IOException e) {
        // presumably this Hudson doesn't use CSRF protection
    }

    // write the output to a temporary file first.
    File tmpFile = File.createTempFile("jenkins", "log");
    try {
        int ret;
        try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
                Writer w = new OutputStreamWriter(os, "UTF-8")) {
            w.write("<?xml version='1.1' encoding='UTF-8'?>");
            w.write("<run><log encoding='hexBinary' content-encoding='" + Charset.defaultCharset().name()
                    + "'>");
            w.flush();

            // run the command
            long start = System.currentTimeMillis();

            List<String> cmd = new ArrayList<String>();
            for (int i = 1; i < args.length; i++)
                cmd.add(args[i]);
            Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in,
                    new DualOutputStream(System.out, new EncodingStream(os)));

            ret = proc.join();

            w.write("</log><result>" + ret + "</result><duration>" + (System.currentTimeMillis() - start)
                    + "</duration></run>");
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }

        URL location = new URL(jobURL, "postBuildResult");
        while (true) {
            try {
                // start a remote connection
                HttpURLConnection con = open(location);
                if (auth != null)
                    con.setRequestProperty("Authorization", auth);
                if (crumbField != null && crumbValue != null) {
                    con.setRequestProperty(crumbField, crumbValue);
                }
                con.setDoOutput(true);
                // this tells HttpURLConnection not to buffer the whole thing
                con.setFixedLengthStreamingMode((int) tmpFile.length());
                con.connect();
                // send the data
                try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
                    org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }

                if (con.getResponseCode() != 200) {
                    org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
                }

                return ret;
            } catch (HttpRetryException e) {
                if (e.getLocation() != null) {
                    // retry with the new location
                    location = new URL(e.getLocation());
                    continue;
                }
                // otherwise failed for reasons beyond us.
                throw e;
            }
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final synchronized void download(URL url, String version, String export, List<String> driverName)
        throws IOException {
    File targetFile = new File(getTarget(version, url));
    File binary = null;//w ww .ja va2 s . co m

    // Check if binary exists
    boolean download = !targetFile.getParentFile().exists()
            || (targetFile.getParentFile().exists() && targetFile.getParentFile().list().length == 0)
            || WdmConfig.getBoolean("wdm.override");

    if (!download) {
        // Check if existing binary is valid
        Collection<File> listFiles = FileUtils.listFiles(targetFile.getParentFile(), null, true);
        for (File file : listFiles) {
            for (String s : driverName) {
                if (file.getName().startsWith(s) && file.canExecute()) {
                    binary = file;
                    log.debug("Using binary driver previously downloaded {}", binary);
                    download = false;
                    break;
                } else {
                    download = true;
                }
            }
            if (!download) {
                break;
            }
        }
    }

    if (download) {
        log.info("Downloading {} to {}", url, targetFile);
        HttpURLConnection conn = getConnection(url);
        int responseCode = conn.getResponseCode();
        log.debug("Response HTTP {}", responseCode);
        if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
            // HTTP Redirect
            URL newUrl = new URL(conn.getHeaderField("Location"));
            log.debug("Redirect to {}", newUrl);
            conn = getConnection(newUrl);
        }

        FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile);

        if (!export.contains("edge")) {
            binary = extract(targetFile, export);
            targetFile.delete();
        } else {
            binary = targetFile;
        }

    }
    if (export != null) {
        BrowserManager.exportDriver(export, binary.toString());
    }

}

From source file:core.Utility.java

private static ArrayList<String> getSynonymsWiktionary(String _word) throws MalformedURLException, IOException {
    ArrayList<String> _list = new ArrayList();
    try {//w  w  w  . jav  a 2 s . c  om

        URL url = new URL("http://www.igrec.ca/project-files/wikparser/wikparser.php?word=" + _word
                + "&query=syn&lang=en");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        while ((output = br.readLine()) != null) {
            boolean isEmpty = output.contains("No listed synonyms.")
                    || output.contains("ERROR: The Wiktionary API did not return a page for that word.");

            if (isEmpty) {
                conn.disconnect();
                return _list;
            } else {
                String[] arr = output.trim().split(" ");
                for (String s : arr) {
                    if (s.length() > 2) {
                        _list.add(s);
                    }
                }
            }
        }

        conn.disconnect();

    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return _list;
}