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.zack6849.alphabot.api.Utils.java

public static String getTitle(String link) {
    String response = "";
    try {/*from   www .  j av  a2 s  .com*/
        HttpURLConnection conn = (HttpURLConnection) new URL(link).openConnection();
        conn.addRequestProperty("User-Agent", USER_AGENT);
        String type = conn.getContentType();
        int length = conn.getContentLength() / 1024;
        response = String.format("HTTP %s: %s", conn.getResponseCode(), conn.getResponseMessage());
        String info;
        if (type.contains("text") || type.contains("application")) {
            Document doc = Jsoup.connect(link).userAgent(USER_AGENT).followRedirects(true).get();
            String title = doc.title() == null || doc.title().isEmpty() ? "No title found!" : doc.title();
            info = String.format("%s - (Content Type: %s Size: %skb)", title, type, length);
            return info;
        }
        info = String.format("Content Type: %s Size: %skb", type, length);
        return info;

    } catch (IOException ex) {
        if (ex.getMessage().contains("UnknownHostException")) {
            return Colors.RED + "Unknown hostname!";
        }
        return response.isEmpty() ? Colors.RED + "An error occured" : response;
    }
}

From source file:Main.java

/**
 * Given a string url, connects and returns response code
 *
 * @param urlString       string to fetch
 * @param network       network/*from   w w  w.  j ava2  s . c  o m*/
 * @param readTimeOutMs       read time out
 * @param connectionTimeOutMs       connection time out
 * @param urlRedirect       should use urlRedirect
 * @param useCaches       should use cache
 * @return httpResponseCode http response code
 * @throws IOException
 */

@TargetApi(LOLLIPOP)
public static int checkUrlWithOptionsOverNetwork(String urlString, Network network, int readTimeOutMs,
        int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException {
    if (network == null) {
        return -1;
    }
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) network.openConnection(url);
    connection.setReadTimeout(readTimeOutMs /* milliseconds */);
    connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */);
    connection.setRequestMethod("GET");
    connection.setInstanceFollowRedirects(urlRedirect);
    connection.setUseCaches(useCaches);
    // Starts the query
    connection.connect();
    int responseCode = connection.getResponseCode();
    connection.disconnect();
    return responseCode;
}

From source file:Main.java

private static String httpPost(String address, String params) {
    InputStream inputStream = null;
    HttpURLConnection urlConnection = null;
    try {/*from ww  w  .  j a v a 2  s .c om*/
        URL url = new URL(address);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.getOutputStream().write(params.getBytes());
        urlConnection.getOutputStream().flush();

        urlConnection.connect();
        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            StringBuffer stringBuffer = new StringBuffer();
            while ((len = inputStream.read(buffer)) != -1) {
                stringBuffer.append(new String(buffer, 0, len));
            }
            return stringBuffer.toString();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(inputStream);
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;

}

From source file:be.roots.taconic.pricingguide.util.HttpUtil.java

private static HttpURLConnection getInputStreamFor(String urlAsString, String userName, String password)
        throws IOException {
    LOGGER.info(/*w  w w.j av a 2s.c o m*/
            REQUEST_METHOD + "ting data from url: " + urlAsString + " with timeout set to " + CONNECT_TIMEOUT);

    final URL url = new URL(urlAsString);
    final HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod(REQUEST_METHOD);
    con.setConnectTimeout(CONNECT_TIMEOUT);

    if (userName != null || password != null) {
        final String encoded = Base64.encode(userName + ":" + password);
        con.setRequestProperty("Authorization", "Basic " + encoded);
    }

    final int responseCode = con.getResponseCode();

    LOGGER.info("Response code: " + responseCode);
    return con;
}

From source file:imageLines.ImageHelpers.java

/**Read a jpeg image from a url into a BufferedImage*/
public static BufferedImage readAsBufferedImage(URL imageURL, String cookieVal) {
    InputStream i = null;/*from www.j a v a  2  s .c o m*/
    try {
        HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();

        conn.setRequestProperty("Cookie", cookieVal);
        int responseCode = conn.getResponseCode();

        if (responseCode == 200 || responseCode == 304) {
            System.out.print("good response" + responseCode + "\n");

        } else {
            System.out.print("bad response " + responseCode + "\n");

        }

        i = conn.getInputStream();
        //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(i);
        BufferedImage bi = ImageIO.read(i);//decoder.decodeAsBufferedImage();
        return bi;
    } catch (Exception e) {
        System.out.println(e);
        return null;
    } finally {
        try {
            if (i != null)
                i.close();
        } catch (IOException ex) {

        }
    }
}

From source file:com.andrious.btc.data.jsonUtils.java

private static HttpURLConnection urlConnect(String urlString) throws IOException {

    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("GET");

    conn.setRequestProperty("Accept", "application/json");

    int response = conn.getResponseCode();

    if (response != HttpURLConnection.HTTP_OK) {

        if (!handleResponse(response, conn)) {

            throw new RuntimeException("Failed : HTTP error code : " + response);
        }//from ww  w  . j  av a 2s. c om
    }

    return conn;
}

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

public static Project getProject(Project p) throws IOException {

    // Server URL setup
    String _url = getBaseUri().appendPath(p.getProjectID()).build().toString();

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

    // add request header
    conn.setRequestMethod("GET");
    addRequestHeader(conn, false);/* www. j a  va  2  s  .com*/

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

    return parseProject(projectNode, p);
}

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

public static void deleteProject(Project p) throws IOException {

    // Server URL setup
    String _url = getBaseUri().appendPath(p.getProjectID()).build().toString();

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

    // add request header
    conn.setRequestMethod("DELETE");
    addRequestHeader(conn, false);//from   w ww .  j av a2 s  .  c o m

    // Get server response
    conn.getResponseCode();
    getServerResponse(conn);

}

From source file:fr.haploid.webservices.WebServicesHelper.java

protected static synchronized WebServicesResponseData downloadFromServer(String url, JSONObject params,
        String type) {//from  www .  j a  v a  2s .c  o m

    int responseCode = 9999;

    StringBuffer buffer = new StringBuffer();

    Uri.Builder builder = new Uri.Builder();
    builder.encodedPath(url);

    JSONArray namesOfParams = params.names();

    for (int i = 0; i < namesOfParams.length(); i++) {
        try {
            String param = namesOfParams.getString(i);
            builder.appendQueryParameter(param, params.get(param).toString());
        } catch (JSONException e) {
            return new WebServicesResponseData("JSONException " + e.toString(), responseCode, false);
        }
    }

    URL urlBuild;

    try {
        urlBuild = new URL(builder.build().toString());
    } catch (MalformedURLException e) {
        return new WebServicesResponseData("MalformedURLException " + e.toString(), responseCode, false);
    }

    try {
        HttpURLConnection urlConnection = (HttpURLConnection) urlBuild.openConnection();
        try {
            urlConnection.setRequestMethod(type);
        } catch (ProtocolException e) {
            return new WebServicesResponseData("ProtocolException " + e.toString(), responseCode, false);
        }

        urlConnection.connect();
        responseCode = urlConnection.getResponseCode();
        if (responseCode < 400) {
            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream == null) {
                return new WebServicesResponseData(null, responseCode, false);
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                return new WebServicesResponseData(null, responseCode, false);
            }
        }
    } catch (IOException e) {
        return new WebServicesResponseData("IOException " + e.toString(), responseCode, false);
    }
    return new WebServicesResponseData(buffer.toString(), responseCode, true);
}

From source file:com.thomaskuenneth.openweathermapweather.WeatherUtils.java

public static String getFromServer(String url) throws MalformedURLException, IOException {
    StringBuilder sb = new StringBuilder();
    URL _url = new URL(url);
    HttpURLConnection httpURLConnection = (HttpURLConnection) _url.openConnection();
    String contentType = httpURLConnection.getContentType();
    String charSet = "ISO-8859-1";
    if (contentType != null) {
        Matcher m = PATTERN_CHARSET.matcher(contentType);
        if (m.matches()) {
            charSet = m.group(1);//from w w  w. j a  v a 2 s  .  c  o m
        }
    }
    final int responseCode = httpURLConnection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream(),
                charSet);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, "getFromServer()", ex);
        }
    }
    httpURLConnection.disconnect();
    return sb.toString();
}