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:Main.java

/**
 * On some devices we have to hack:/*from w  w w . jav a 2  s.co  m*/
 * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html
 * @return the resolved url if any. Or null if it couldn't resolve the url
 * (within the specified time) or the same url if response code is OK
 */
public static String getResolvedUrl(String urlAsString, int timeout) {
    try {
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        // force no follow

        hConn.setInstanceFollowRedirects(false);
        // the program doesn't care what the content actually is !!
        // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html
        hConn.setRequestMethod("HEAD");
        // default is 0 => infinity waiting
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        hConn.connect();
        int responseCode = hConn.getResponseCode();
        hConn.getInputStream().close();
        if (responseCode == HttpURLConnection.HTTP_OK)
            return urlAsString;

        String loc = hConn.getHeaderField("Location");
        if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null)
            return loc.replaceAll(" ", "+");

    } catch (Exception ex) {
    }
    return "";
}

From source file:Main.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *///www  . j  a v a2 s  .  c  o  m
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        /*
        If the request was successful (response code 200),
        then read the input stream and parse the response.
         */
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            //handle exception
        }
    } catch (IOException e) {
        //handle exception
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:org.apache.hadoop.hdfs.web.ByteRangeInputStream.java

private static long getStreamLength(HttpURLConnection connection, Map<String, List<String>> headers)
        throws IOException {
    String cl = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);
    if (cl == null) {
        // Try to get the content length by parsing the content range
        // because HftpFileSystem does not return the content length
        // if the content is partial.
        if (connection.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT) {
            cl = connection.getHeaderField(HttpHeaders.CONTENT_RANGE);
            return getLengthFromRange(cl);
        } else {//from ww  w. j  ava 2  s. co m
            throw new IOException(HttpHeaders.CONTENT_LENGTH + " is missing: " + headers);
        }
    }
    return Long.parseLong(cl);
}

From source file:ilearnrw.utils.ServerHelperClass.java

public static String sendPost(String link, String urlParameters) throws Exception {
    String url = baseUrl + link;//from w w  w . j a va 2s.co  m

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api"));

    con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    con.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF8");

    wr.write(urlParameters);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    return response.toString();
}

From source file:com.openforevent.main.UserPosition.java

public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context)
        throws IOException {
    URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip
            + "&format=xml");
    //URL url = new URL("http://ipinfodb.com/ip_query.php");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);//from   ww w . j a  v a  2 s  .  c  o  m
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Retrieve the output
    int responseCode = urlConnection.getResponseCode();
    InputStream inputStream;
    if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = urlConnection.getInputStream();
    } else {
        inputStream = urlConnection.getErrorStream();
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String theString = writer.toString();

    Debug.logInfo("Get user position by IP stream is = ", theString);

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("stream", theString);
    return paramOut;
}

From source file:com.andrew.apollo.cache.ImageFetcher.java

/**
 * Download a {@link Bitmap} from a URL, write it to a disk and return the
 * File pointer. This implementation uses a simple disk cache.
 *
 * @param context The context to use// w  ww.java2  s.c  o  m
 * @param urlString The URL to fetch
 * @return A {@link File} pointing to the fetched bitmap
 */
public static final File downloadBitmapToFile(final Context context, final String urlString,
        final String uniqueName) {
    final File cacheDir = ImageCache.getDiskCacheDir(context, uniqueName);

    if (!cacheDir.exists()) {
        cacheDir.mkdir();
    }

    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;

    try {
        final File tempFile = File.createTempFile("bitmap", null, cacheDir); //$NON-NLS-1$

        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        final InputStream in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
        out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES);

        int oneByte;
        while ((oneByte = in.read()) != -1) {
            out.write(oneByte);
        }
        return tempFile;
    } catch (final IOException ignored) {
        ignored.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ignored) {
            }
        }
    }
    return null;
}

From source file:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java

/**
 * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses.
 *
 * @param destination URL of the OCSP response provider
 * @return list of OCSP response objects
 * @throws IOException   if I/O errors occurred
 * @throws OCSPException if the response could not be parsed
 *///from  w  w  w.j a  v a 2 s.c  om
public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED);
    connection.setDoOutput(true);
    connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout());
    connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout());
    connection.setRequestMethod(METHOD);
    connection.connect();

    if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) {
        log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(),
                connection.getResponseMessage());

        throw new IOException(connection.getResponseMessage());
    }

    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build();

    final List<OCSPResp> responses = new ArrayList<>();
    final MimeStreamParser parser = new MimeStreamParser(config);

    parser.setContentHandler(new AbstractContentHandler() {
        @Override
        public void startMultipart(BodyDescriptor bd) {
            parser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException {
            if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) {
                responses.add(new OCSPResp(IOUtils.toByteArray(is)));
            }
        }
    });

    try {
        parser.parse(connection.getInputStream());
    } catch (MimeException e) {
        throw new OCSPException("Error parsing response", e);
    }

    return responses;
}

From source file:bakuposter.gcm.server.POST2GCMessage.java

public static void post(String apiKey, Content content) {

    try {/* w w  w.jav  a  2  s. co m*/
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);
        conn.setDoOutput(true);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(content.getRegistration_ids().get(0));
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        mapper.writeValue(wr, content);
        wr.flush();
        wr.close();
        int responseCode = conn.getResponseCode();
        System.out.println("responseCode = " + responseCode);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.edgenius.wiki.Shell.java

/**
 * @param url/*from  ww w .ja  v  a  2 s  . co m*/
 * @return
 */
private static boolean notifyShell(String url) {
    if (StringUtils.isEmpty(Shell.key)) {
        //I suppose all notify methods will execute in backend thread, i.e.,  MQ consumer. This won't use new thread to avoid thread block.  
        if (!requestInstanceShellKey()) {
            log.error("Unable to locate Shell key value from shell hosting {}", url);
            return false;
        }
    }

    try {
        log.info("Notify shell {}", url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty(HEAD_SHELL_KEY, Shell.key);

        conn.setConnectTimeout(timeout);
        return (conn.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (IOException e) {
        log.error("Unable to connect shell for notification", e);
    } catch (Throwable e) {
        log.error("Notify shell failure", e);
    }

    return false;
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static CypherSession userLogin(String username, byte[] serverPassword, byte[] localPassword)
        throws IOException, APIErrorException {
    String passwordHashEncoded = Utils.BASE64_URL.encode(serverPassword);

    HttpURLConnection conn = doRequest("login", null, new String[] { "username", "password" },
            new String[] { username, passwordHashEncoded });

    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }/*w  w w .ja va2  s.c om*/

    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode == StatusCode.OK) {
        long userID = node.get("userID").asLong();
        ECKey key;
        try {
            key = Utils.decodeKey(node.get("publicKey").asText(), node.get("privateKey").asText(),
                    localPassword);
        } catch (InvalidCipherTextException ex) {
            throw new RuntimeException(ex);
        }
        long keyTimestamp = node.get("keyTimestamp").asLong();
        key.setTime(keyTimestamp);
        CypherUser newUser = new CypherUser(username, localPassword, serverPassword, userID, key, keyTimestamp);
        String sessionID = node.get("sessionID").asText();
        return new CypherSession(newUser, sessionID);
    } else {
        throw new APIErrorException(statusCode);
    }
}