Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

In this page you can find the example usage for java.net HttpURLConnection getHeaderField.

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:net.servicestack.client.JsonServiceClient.java

public static RuntimeException createException(HttpURLConnection res, int responseCode) {

    WebServiceException webEx = null;
    try {//from   ww w  .ja  v a  2s .  c  o m
        String responseBody = Utils.readToEnd(res.getErrorStream(), UTF8.name());
        webEx = new WebServiceException(responseCode, res.getResponseMessage(), responseBody);

        if (Utils.matchesContentType(res.getHeaderField(HttpHeaders.ContentType), MimeTypes.Json)) {
            JSONObject jResponse = new JSONObject(responseBody);

            Iterator<?> keys = jResponse.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String varName = Utils.sanitizeVarName(key);
                if (varName.equals("responsestatus")) {
                    webEx.setResponseStatus(Utils.createResponseStatus(jResponse.get(key)));
                    break;
                }
            }
        }

        return webEx;

    } catch (IOException e) {
        if (webEx != null) {
            return webEx;
        }
        return new RuntimeException(e);
    } catch (JSONException e) {
        if (webEx != null) {
            return webEx;
        }
        return new RuntimeException(e);
    }
}

From source file:och.util.NetUtil.java

public static String invokeGet(HttpURLConnection conn) throws IOException {

    try {//from  w w w .j av a 2 s .co m

        int code = conn.getResponseCode();
        //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
        if (code == -1) {
            throw new IllegalStateException("NetUtil: conn.getResponseCode() return -1");
        }

        InputStream is = new BufferedInputStream(conn.getInputStream());
        String enc = conn.getHeaderField("Content-Encoding");
        if (enc != null && enc.equalsIgnoreCase("gzip")) {
            is = new GZIPInputStream(is);
        }

        String response = streamToStr(is);
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:Main.java

public static URI unredirect(URI uri) throws IOException {
    if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
        return uri;
    }//from  w w  w . j  a v a2s .  c o m
    URL url = uri.toURL();

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(false);
    connection.setDoInput(false);
    connection.setRequestMethod("HEAD");
    connection.setRequestProperty("User-Agent", "ZXing (Android)");
    try {
        connection.connect();
        switch (connection.getResponseCode()) {
        case HttpURLConnection.HTTP_MULT_CHOICE:
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
        case HttpURLConnection.HTTP_SEE_OTHER:
        case 307: // No constant for 307 Temporary Redirect ?
            String location = connection.getHeaderField("Location");
            if (location != null) {
                try {
                    return new URI(location);
                } catch (URISyntaxException e) {
                    // nevermind
                }
            }
        }
        return uri;
    } finally {
        connection.disconnect();
    }
}

From source file:tablefromdbpedia.TableFromDBPedia.java

public static void downloadFile(String entityID) throws IOException {
    String fileURL = "http://dbpedia.org/data/" + entityID + ".rdf";
    String saveDir = inputFolder;
    URL url = new URL(fileURL);
    HttpURLConnection httpConn;// = (HttpURLConnection) url.openConnection();
    int responseCode;// = httpConn.getResponseCode();
    do {//from  ww  w.  j a  v a 2  s. c  o m
        httpConn = (HttpURLConnection) url.openConnection();
        responseCode = httpConn.getResponseCode();
    } while (responseCode != HttpURLConnection.HTTP_OK);

    // always check HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        System.out.println("Downloading for: " + entityID);
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");

        if (disposition != null) {
            // extracts file name from header field
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 10, disposition.length() - 1);
            }
        } else {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
        }

        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + File.separator + fileName;

        // opens an output stream to save into file
        //saveFilePath.replace(".rdf", ".txt");
        String downloadAt = inputFolder + entityID + ".txt";
        FileOutputStream outputStream = new FileOutputStream(downloadAt);

        int bytesRead = -1;
        byte[] buffer = new byte[4096];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();

        //System.out.println("File downloaded");
    } else {
        System.out.println("Download Failed. Server replied HTTP code: " + responseCode);
    }
    httpConn.disconnect();
}

From source file:net.technicpack.launchercore.util.DownloadUtils.java

public static String getETag(String address) {
    String md5 = "";

    try {/* w w w .  j  a  va  2  s .  co  m*/
        URL url = new URL(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);

        String eTag = conn.getHeaderField("ETag");
        if (eTag != null) {
            eTag = eTag.replaceAll("^\"|\"$", "");
            if (eTag.length() == 32) {
                md5 = eTag;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return md5;
}

From source file:org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTransport.java

private static void readStream(HttpURLConnection conn, ServiceResult result) throws Throwable {
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    try {/*from w  w w .  j  a v  a 2s .  c  o  m*/
        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            sb.append(line).append("\r\n");
        }
        String msg = sb.toString();
        result.result = msg;
        result.boundary = PayloadLogger.parseBoundary(conn.getHeaderField("CONTENT-TYPE"));
    } finally {
        rd.close();
    }
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param repoURL - URL on the repo/*from w  w  w.  j a v a  2 s. c  om*/
 * @param fullDebug - should this dump the full cloudflare debug info in the console
 * @return boolean representing if the file exists
 */
public static boolean CloudFlareInspector(String repoURL, boolean fullDebug) {
    try {
        boolean ret;
        HttpURLConnection connection = (HttpURLConnection) new URL(repoURL + "cdn-cgi/trace").openConnection();
        if (!fullDebug)
            connection.setRequestMethod("HEAD");
        Logger.logInfo("CF-RAY: " + connection.getHeaderField("CF-RAY"));
        if (fullDebug)
            Logger.logInfo("CF Debug Info: " + connection.getContent().toString());
        ret = connection.getResponseCode() == 200;
        IOUtils.close(connection);
        return ret;
    } catch (Exception e) {
        return false;
    }
}

From source file:Main.java

/**
 * Return an {@link InputStream} from the given url or null if failed to retrieve the content
 * /*from   w  w w.  j  a v  a 2  s.  c  om*/
 * @param uri
 * @return
 */
static InputStream openRemoteInputStream(Uri uri) {
    java.net.URL finalUrl;
    try {
        finalUrl = new java.net.URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }

    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) finalUrl.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    connection.setInstanceFollowRedirects(false);
    int code;
    try {
        code = connection.getResponseCode();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    // permanent redirection
    if (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP
            || code == HttpURLConnection.HTTP_SEE_OTHER) {
        String newLocation = connection.getHeaderField("Location");
        return openRemoteInputStream(Uri.parse(newLocation));
    }

    try {
        return (InputStream) finalUrl.getContent();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:de.darkblue.bongloader2.utils.ToolBox.java

/**
 * returns the file size using the config to retrieve the current version of
 * bongloader and setting the right user-agent
 *
 * @param config/*  w w  w . j a v a2 s.com*/
 * @param url
 * @return
 * @throws IOException
 */
public static long getFileSize(final Configuration config, final URL url) throws IOException {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        if (config != null) {
            connection.setRequestProperty("User-Agent", "BongLoader2 " + config.get(ConfigurationKey.VERSION));
        }
        connection.setConnectTimeout(2000);
        connection.connect();

        final String headerField = connection.getHeaderField("Content-Length");
        if (headerField == null) {
            throw new IOException("Did not get a content length for the connection to " + url);
        }

        final String rawContentLength = headerField.trim();
        return Long.valueOf(rawContentLength);
        //return connection.getContentLength();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.alexoree.jenkins.Main.java

private static String download(String localName, String remoteUrl) throws Exception {
    URL obj = new URL(remoteUrl);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
    conn.setReadTimeout(5000);// ww w. j  a v a 2s.c  o  m

    System.out.println("Request URL ... " + remoteUrl);

    boolean redirect = false;

    // normally, 3xx is redirect
    int status = conn.getResponseCode();
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            redirect = true;
    }

    if (redirect) {

        // get redirect url from "location" header field
        String newUrl = conn.getHeaderField("Location");

        // get the cookie if need, for login
        String cookies = conn.getHeaderField("Set-Cookie");

        // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();

        String version = newUrl.substring(newUrl.lastIndexOf("/", newUrl.lastIndexOf("/") - 1) + 1,
                newUrl.lastIndexOf("/"));
        String pluginname = localName.substring(localName.lastIndexOf("/") + 1);
        String ext = "";
        if (pluginname.endsWith(".war"))
            ext = ".war";
        else
            ext = ".hpi";

        pluginname = pluginname.replace(ext, "");
        localName = localName.replace(pluginname + ext,
                "/download/plugins/" + pluginname + "/" + version + "/");
        new File(localName).mkdirs();
        localName += pluginname + ext;
        System.out.println("Redirect to URL : " + newUrl);

    }
    if (new File(localName).exists()) {
        System.out.println(localName + " exists, skipping");
        return localName;
    }

    byte[] buffer = new byte[2048];

    FileOutputStream baos = new FileOutputStream(localName);
    InputStream inputStream = conn.getInputStream();
    int totalBytes = 0;
    int read = inputStream.read(buffer);
    while (read > 0) {
        totalBytes += read;
        baos.write(buffer, 0, read);
        read = inputStream.read(buffer);
    }
    System.out.println("Retrieved " + totalBytes + "bytes");

    return localName;

}