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.technicpack.utilslib.Utils.java

/**
 * Opens an HTTP connection to a web URL and tests that the response is a valid 200-level code
 * and we can successfully open a stream to the content.
 *
 * @param urlLoc The HTTP URL indicating the location of the content.
 * @return True if the content can be accessed successfully, false otherwise.
 *///from  w w w .j  a va  2  s. c om
public static boolean pingHttpURL(String urlLoc, MirrorStore mirrorStore) {
    InputStream stream = null;
    try {
        final URL url = mirrorStore.getFullUrl(urlLoc);
        HttpURLConnection conn = openHttpConnection(url);

        int responseCode = conn.getResponseCode();
        int responseFamily = responseCode / 100;

        if (responseFamily == 3) {
            String newUrl = conn.getHeaderField("Location");
            URL redirectUrl = null;
            try {
                redirectUrl = new URL(newUrl);
            } catch (MalformedURLException ex) {
                throw new DownloadException("Invalid Redirect URL: " + url, ex);
            }

            conn = openHttpConnection(redirectUrl);
            responseCode = conn.getResponseCode();
            responseFamily = responseCode / 100;
        }

        if (responseFamily == 2) {
            stream = conn.getInputStream();
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        return false;
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.rapidcontext.app.plugin.http.HttpPostProcedure.java

/**
 * Logs the HTTP response to the procedure call context.
 *
 * @param cx             the procedure call context
 * @param con            the HTTP connection
 * @param data           the HTTP response data
 *
 * @throws IOException if the HTTP response couldn't be extracted
 *//*  w  w w .  j a  v  a  2 s.  co m*/
private static void logResponse(CallContext cx, HttpURLConnection con, String data) throws IOException {

    cx.log(con.getHeaderField(0));
    for (int i = 1; true; i++) {
        String key = con.getHeaderFieldKey(i);
        if (key == null) {
            break;
        }
        cx.log("  " + key + ": " + con.getHeaderField(i));
    }
    if (data != null) {
        cx.log(data);
    }
}

From source file:Main.java

@SuppressLint("NewApi")
public static void getURL(String path) {
    String fileName = "";
    String dir = "/IndoorNavi/";
    File sdRoot = Environment.getExternalStorageDirectory();
    try {/*w  w  w . j  a v a2 s  . c om*/
        // Open the URLConnection for reading
        URL u = new URL(path);
        // URL u = new URL("http://www.baidu.com/");
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();

        int code = uc.getResponseCode();
        String response = uc.getResponseMessage();
        //System.out.println("HTTP/1.x " + code + " " + response);
        for (int j = 1;; j++) {
            String key = uc.getHeaderFieldKey(j);
            String header = uc.getHeaderField(j);
            if (!(key == null)) {
                if (key.equals("Content-Name"))
                    fileName = header;
            }
            if (header == null || key == null)
                break;
            //System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
        }
        Log.i("zhr", fileName);
        //System.out.println();

        try (InputStream in = new BufferedInputStream(uc.getInputStream())) {

            // chain the InputStream to a Reader
            Reader r = new InputStreamReader(in);
            int c;
            File mapFile = new File(sdRoot, dir + fileName);
            mapFile.createNewFile();
            FileOutputStream filecon = new FileOutputStream(mapFile);
            while ((c = r.read()) != -1) {
                //System.out.print((char) c);
                filecon.write(c);
                filecon.flush();

            }
            filecon.close();
        }

    } catch (MalformedURLException ex) {
        System.err.println(path + " is not a parseable URL");
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

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  . j  av  a  2  s. c om*/
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:org.elegosproject.romupdater.DownloadManager.java

public static boolean sendAnonymousData() {
    String link = "http://www.elegosproject.org/android/upload.php";
    String data;/*from  w  w  w.ja  va  2  s . c o m*/

    SharedData shared = SharedData.getInstance();
    String romName = shared.getRepositoryROMName();
    String romVersion = shared.getDownloadVersion();
    String romPhone = shared.getRepositoryModel();
    String romRepository = shared.getRepositoryUrl();

    if (romName.equals("") || romVersion.equals("") || romPhone.equals("") || romRepository.equals("")) {
        Log.e(TAG, "Internal error - missing system variables.");
        return false;
    }

    if (!checkHttpFile(link))
        return false;
    try {
        data = URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(romPhone, "UTF-8");
        data += "&" + URLEncoder.encode("rom_name", "UTF-8") + "=" + URLEncoder.encode(romName, "UTF-8");
        data += "&" + URLEncoder.encode("rom_version", "UTF-8") + "=" + URLEncoder.encode(romVersion, "UTF-8");
        data += "&" + URLEncoder.encode("rom_repository", "UTF-8") + "="
                + URLEncoder.encode(romRepository, "UTF-8");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);

        URL url = new URL(link);
        url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "ROMUpdater");
        conn.setDoOutput(true);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.println(data);
        out.close();

        int status = Integer.parseInt(conn.getHeaderField("ROMUpdater-status"));
        if (status == 1)
            return true;

        Log.e(TAG, "It was impossible to send data to the stastistics server ("
                + conn.getHeaderField("ROMUpdater-error") + ").");
        return false;

    } catch (Exception e) {
        Log.e(TAG, "It was impossible to send data to the stastistics server.");
        Log.e(TAG, "Error: " + e.toString());
        return false;
    }
}

From source file:org.openbravo.test.datasource.DatasourceTestUtil.java

static String authenticate(String openbravoURL, String user, String password) throws Exception {
    final HttpURLConnection hc = DatasourceTestUtil.createConnection(openbravoURL,
            "/secureApp/LoginHandler.html", "POST", null);
    final OutputStream os = hc.getOutputStream();
    String content = "user=" + user + "&password=" + password;
    os.write(content.getBytes("UTF-8"));
    os.flush();//from  www  . j a v  a  2s .c o  m
    os.close();
    hc.connect();
    return hc.getHeaderField("Set-Cookie");
}

From source file:org.rhq.plugins.www.util.WWWUtils.java

/**
 * Get the content of the 'Server' header.
 *
 * @param httpURL a http or https URL to get the header from
 * @return the contents of the header or null if anything went wrong or the field was not present.
 *//*from  w  ww  .  j  a  v  a2 s .co m*/
public static String getServerHeader(URL httpURL) {
    String ret;

    try {
        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
        connection.setRequestMethod("HEAD");
        connection.setConnectTimeout(3000);
        connection.setReadTimeout(1000);

        connection.connect();
        // get the response code to actually trigger sending the Request.
        connection.getResponseCode();
        ret = connection.getHeaderField("Server");
    } catch (IOException e) {
        ret = null;
    }
    return ret;
}

From source file:org.omegat.util.WikiGet.java

/**
 * Parse response as string.//from w  w  w  .ja v a 2 s . com
 */
private static String getStringContent(HttpURLConnection conn) throws IOException {
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new ResponseError(conn);
    }
    String contentType = conn.getHeaderField("Content-Type");
    int cp = contentType != null ? contentType.indexOf(CHARSET_MARK) : -1;
    String charset = cp >= 0 ? contentType.substring(cp + CHARSET_MARK.length()) : "ISO8859-1";

    try (InputStream in = conn.getInputStream()) {
        return IOUtils.toString(in, charset);
    }
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

private static InputStream getInputStream(HttpURLConnection httpUrlConnection) throws IOException {
    InputStream inputStream = httpUrlConnection.getInputStream();
    String contentEncoding = httpUrlConnection.getHeaderField("Content-Encoding");
    if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
        inputStream = new GZIPInputStream(inputStream);
    }/*from   www. ja v a 2  s.  c om*/
    return inputStream;
}

From source file:org.apache.hadoop.yarn.client.TestRMFailover.java

static String getRefreshURL(String url) {
    String redirectUrl = null;/*from   w w w .  j  av a 2  s . c om*/
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        // do not automatically follow the redirection
        // otherwise we get too many redirections exception
        conn.setInstanceFollowRedirects(false);
        redirectUrl = conn.getHeaderField("Refresh");
    } catch (Exception e) {
        // throw new RuntimeException(e);
    }
    return redirectUrl;
}