Java Code Examples for java.net.URLConnection#getHeaderField()

The following examples show how to use java.net.URLConnection#getHeaderField() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
private void maybeDrainQueue() {
  synchronized (sendQueue) {
    if (appRTCSignalingParameters == null) {
      return;
    }
    try {
      for (String msg : sendQueue) {
        URLConnection connection = new URL(
            appRTCSignalingParameters.gaeBaseHref +
            appRTCSignalingParameters.postMessageUrl).openConnection();
        connection.setDoOutput(true);
        connection.getOutputStream().write(msg.getBytes("UTF-8"));
        if (!connection.getHeaderField(null).startsWith("HTTP/1.1 200 ")) {
          throw new IOException(
              "Non-200 response to POST: " + connection.getHeaderField(null) +
              " for msg: " + msg);
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    sendQueue.clear();
  }
}
 
Example 2
Source Project: arthas   File: DownloadUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * support redirect
 *
 * @param url
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
private static URLConnection openURLConnection(String url) throws MalformedURLException, IOException {
    URLConnection connection = new URL(url).openConnection();
    if (connection instanceof HttpURLConnection) {
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        // normally, 3xx is redirect
        int status = ((HttpURLConnection) connection).getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER) {
                String newUrl = connection.getHeaderField("Location");
                AnsiLog.debug("Try to open url: {}, redirect to: {}", url, newUrl);
                return openURLConnection(newUrl);
            }
        }
    }
    return connection;
}
 
Example 3
Source Project: jivejdon   File: TitleExtractor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loops through response headers until Content-Type is found.
 * 
 * @param conn
 * @return ContentType object representing the value of the Content-Type
 *         header
 */
private static ContentType getContentTypeHeader(URLConnection conn) {
	int i = 0;
	boolean moreHeaders = true;
	do {
		String headerName = conn.getHeaderFieldKey(i);
		String headerValue = conn.getHeaderField(i);
		if (headerName != null && headerName.equals("Content-Type"))
			return new ContentType(headerValue);

		i++;
		moreHeaders = headerName != null || headerValue != null;
	} while (moreHeaders);

	return null;
}
 
Example 4
Source Project: Android-Carbon-Forum   File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Boolean saveCookie(Context context, URLConnection connection){
    //获取Cookie
    String headerName=null;
    for (int i=1; (headerName = connection.getHeaderFieldKey(i))!=null; i++) {
        if (headerName.equals("Set-Cookie")) {
            String cookie = connection.getHeaderField(i);
            //将Cookie保存起来
            SharedPreferences mySharedPreferences = context.getSharedPreferences("Session",
                    Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = mySharedPreferences.edit();
            editor.putString("Cookie", cookie);
            editor.apply();
            return true;
        }
    }
    return false;
}
 
Example 5
/**
 * Determines Server (Protocol) Version based on the headers associated
 * with the passed java.net.URLConnection.
 *
 * @param connection The URLCOnnection containing the DAP2 headers
 * @throws DAP2Exception When bad things happen (like the headers are
 *         missing or incorrectly constructed.
 */
public ServerVersion(URLConnection connection) throws DAP2Exception {

  // Did the Server send an XDAP header?
  String sHeader_server = connection.getHeaderField("XDAP");
  if (sHeader_server != null) {
    processXDAPVersion(sHeader_server);
    return;
  }

  // Did the Server send an XDODS-Server header?
  sHeader_server = connection.getHeaderField("XDODS-Server");

  if (sHeader_server == null)
    // Did the Server send an xdods-server header?
    sHeader_server = connection.getHeaderField("xdods-server");


  if (sHeader_server != null) {
    processXDODSServerVersion(sHeader_server);
    return;
  }


  // This is important! If neither of these headers (XDAP or
  // XDODS-Server is present then we are not connected to a real
  // OPeNDAP server. Period. Without the information contained
  // in these headers some data types (Such as Sequence) cannot
  // be correctly serialized/deserialized.

  throw new DAP2Exception("Not a valid OPeNDAP server - " + "Missing MIME Header fields! Either \"XDAP\" "
      + "or \"XDODS-Server.\" must be present.");
}
 
Example 6
Source Project: org.hl7.fhir.core   File: ClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public Calendar getLastModifiedResponseHeaderAsCalendarObject(URLConnection serverConnection) {
  String dateTime = null;
  try {
    dateTime = serverConnection.getHeaderField("Last-Modified");
    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", new Locale("en", "US"));
    Date lastModifiedTimestamp = format.parse(dateTime);
    Calendar calendar=Calendar.getInstance();
    calendar.setTime(lastModifiedTimestamp);
    return calendar;
  } catch(ParseException pe) {
    throw new EFhirClientException("Error parsing Last-Modified response header " + dateTime, pe);
  }
}
 
Example 7
Source Project: org.hl7.fhir.core   File: ClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public Calendar getLastModifiedResponseHeaderAsCalendarObject(URLConnection serverConnection) {
  String dateTime = null;
  try {
    dateTime = serverConnection.getHeaderField("Last-Modified");
    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", new Locale("en", "US"));
    Date lastModifiedTimestamp = format.parse(dateTime);
    Calendar calendar=Calendar.getInstance();
    calendar.setTime(lastModifiedTimestamp);
    return calendar;
  } catch(ParseException pe) {
    throw new EFhirClientException("Error parsing Last-Modified response header " + dateTime, pe);
  }
}
 
Example 8
Source Project: org.hl7.fhir.core   File: ClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public Calendar getLastModifiedResponseHeaderAsCalendarObject(URLConnection serverConnection) {
	String dateTime = null;
	try {
		dateTime = serverConnection.getHeaderField("Last-Modified");
     SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", new Locale("en", "US"));
		Date lastModifiedTimestamp = format.parse(dateTime);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(lastModifiedTimestamp);
		return calendar;
	} catch(ParseException pe) {
		throw new EFhirClientException("Error parsing Last-Modified response header " + dateTime, pe);
	}
}
 
Example 9
Source Project: zxingfragmentlib   File: HttpHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static String getEncoding(URLConnection connection) {
  String contentTypeHeader = connection.getHeaderField("Content-Type");
  if (contentTypeHeader != null) {
    int charsetStart = contentTypeHeader.indexOf("charset=");
    if (charsetStart >= 0) {
      return contentTypeHeader.substring(charsetStart + "charset=".length());
    }
  }
  return "UTF-8";
}
 
Example 10
private void writeLastUpdate(URLConnection connection, Path lastUpdateFile) throws IOException {
    final String etag = connection.getHeaderField(ETAG_HEADER);
    final String content = etag == null ? NO_ETAG : etag;
    final InputStream input = new ByteArrayInputStream(content.getBytes(UTF_8));
    Files.copy(input, lastUpdateFile, REPLACE_EXISTING);
    Log.debug("updated %s with etag %s", lastUpdateFile, content);
}
 
Example 11
public void parse(URL url) throws IOException, ParserConfigurationException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser;

    SSDPDeviceDescriptionParser parser = new SSDPDeviceDescriptionParser(this);

    URLConnection urlConnection = url.openConnection();

    applicationURL = urlConnection.getHeaderField("Application-URL");
    if (applicationURL != null && !applicationURL.substring(applicationURL.length() - 1).equals("/")) {
        applicationURL = applicationURL.concat("/");
    }

    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    Scanner s = null;
    try {
        s = new Scanner(in).useDelimiter("\\A");
        locationXML = s.hasNext() ? s.next() : "";

        saxParser = factory.newSAXParser();
        saxParser.parse(new ByteArrayInputStream(locationXML.getBytes()), parser);
    } finally {
        in.close();
        if (s != null)
            s.close();
    }

    headers = urlConnection.getHeaderFields();
}
 
Example 12
@Override
public Object getContent(URLConnection connection) throws IOException {
    String contentType = connection.getHeaderField("Content-Type");

    String charset = null;
    for (String param : contentType.replace(" ", "").split(";")) {
        if (param.startsWith("charset=")) {
            charset = param.split("=", 2)[1];
            break;
        }
    }

    int bytesRead = -1;
    byte[] buffer = new byte[1024];

    InputStream in = connection.getInputStream();
    FileOutputStream out = new FileOutputStream(uri);
    try {
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    } finally {
        in.close();
        out.close();
    }
    return URI.create(uri);
}
 
Example 13
public static String getConnectionResponseHeaders(URLConnection c) {
  int idx = 0;
  String value;
  StringBuffer buf = new StringBuffer();
  while ((value = c.getHeaderField(idx)) != null) {
    String key = c.getHeaderFieldKey(idx);
    buf.append(key);
    buf.append(": ");
    buf.append(value);
    idx++;
  }
  return buf.toString();
}
 
Example 14
Source Project: netbeans   File: Pump.java    License: Apache License 2.0 5 votes vote down vote up
private void initPumping(URLConnection connection) throws IOException {
    final Date lastModif = new Date(connection.getLastModified());
    final URL realUrl = connection.getURL();
    final String accept = connection.getHeaderField("Accept-Ranges");
    final boolean acceptBytes = accept != null ? accept.contains("bytes"): false;
    final long length = connection.getContentLength();
    pumping.init(realUrl, length, lastModif, acceptBytes);
}
 
Example 15
Source Project: netbeans   File: NetworkAccess.java    License: Apache License 2.0 5 votes vote down vote up
private URLConnection checkRedirect(URLConnection conn, int timeout) throws IOException {
    if (conn instanceof HttpURLConnection) {
        conn.connect();
        int code = ((HttpURLConnection) conn).getResponseCode();
        boolean isInsecure = "http".equalsIgnoreCase(conn.getURL().getProtocol());
        if (code == HttpURLConnection.HTTP_MOVED_TEMP
            || code == HttpURLConnection.HTTP_MOVED_PERM) {
            // in case of redirection, try to obtain new URL
            String redirUrl = conn.getHeaderField("Location"); //NOI18N
            if (null != redirUrl && !redirUrl.isEmpty()) {
                //create connection to redirected url and substitute original connection
                URL redirectedUrl = new URL(redirUrl);
                if (disableInsecureRedirects && (!isInsecure) && (!redirectedUrl.getProtocol().equalsIgnoreCase(conn.getURL().getProtocol()))) {
                    throw new IOException(String.format(
                        "Redirect from secure URL '%s' to '%s' blocked.",
                        conn.getURL().toExternalForm(),
                        redirectedUrl.toExternalForm()
                    ));
                }
                URLConnection connRedir = redirectedUrl.openConnection();
                connRedir.setRequestProperty("User-Agent", "NetBeans"); // NOI18N
                connRedir.setConnectTimeout(timeout);
                connRedir.setReadTimeout(timeout);
                return connRedir;
            }
        }
    }
    return conn;
}
 
Example 16
private long calculateExpiry(URLConnection urlConnection,
        long request_time, UrlConnectionExpiryCalculator
        urlConnectionExpiryCalculator)
{
    if("no-cache".equals(urlConnection.getHeaderField("Pragma"))) {
        return 0L;
    }
    final String cacheControl = urlConnection.getHeaderField(
            "Cache-Control");
    if(cacheControl != null ) {
        if(cacheControl.indexOf("no-cache") != -1) {
            return 0L;
        }
        final int max_age = getMaxAge(cacheControl);
        if(-1 != max_age) {
            final long response_time = System.currentTimeMillis();
            final long apparent_age = Math.max(0, response_time -
                    urlConnection.getDate());
            final long corrected_received_age = Math.max(apparent_age,
                    urlConnection.getHeaderFieldInt("Age", 0) * 1000L);
            final long response_delay = response_time - request_time;
            final long corrected_initial_age = corrected_received_age +
                response_delay;
            final long creation_time = response_time -
                corrected_initial_age;
            return max_age * 1000L + creation_time;
        }
    }
    final long explicitExpiry = urlConnection.getHeaderFieldDate(
            "Expires", -1L);
    if(explicitExpiry != -1L) {
        return explicitExpiry;
    }
    return urlConnectionExpiryCalculator == null ? 0L :
        urlConnectionExpiryCalculator.calculateExpiry(urlConnection);
}
 
Example 17
Source Project: updatefx   File: UpdateDownloadService.java    License: MIT License 4 votes vote down vote up
@Override
protected Task<Path> createTask() {
    return new Task<Path>() {
        @Override
        protected Path call() throws Exception {
            Binary toDownload = null;

            for (Binary binary : release.getBinaries()) {
                if (isCurrentPlatform(binary.getPlatform())) {
                    toDownload = binary;
                    break;
                }
            }

            if (toDownload == null) {
                throw new IllegalArgumentException("This release does not contain binaries for this platform");
            }

            URL fileURL = toDownload.getHref();
            URLConnection connection = fileURL.openConnection();
            connection.connect();

            long len = connection.getContentLengthLong();

            if (len == -1) {
                len = toDownload.getSize();
            }

            updateProgress(0, len);

            String fileName = connection.getHeaderField("Content-Disposition");
            if (fileName != null && fileName.contains("=")) {
                fileName = fileName.split("=")[1];
            } else {
                String url = toDownload.getHref().getPath();
                int lastSlashIdx = url.lastIndexOf('/');

                if (lastSlashIdx >= 0) {
                    fileName = url.substring(lastSlashIdx + 1, url.length());
                } else {
                    fileName = url;
                }
            }

            Path downloadFile = Paths.get(System.getProperty("java.io.tmpdir"), fileName);

            try (OutputStream fos = Files.newOutputStream(downloadFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                 BufferedInputStream is = new BufferedInputStream(connection.getInputStream())) {
                byte[] buffer = new byte[512];
                int n;
                long totalDownload = 0;

                while ((n = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, n);
                    totalDownload += n;
                    updateProgress(totalDownload, len);
                }
            }

            return downloadFile;
        }
    };
}
 
Example 18
public long Download(String strurl, String filedest, long seek) throws IOException {
	try {
		// Setup connection.
        URL url = new URL(strurl);
        URLConnection connection = url.openConnection();
        
        File fdest = new File(filedest);
        connection.connect();
        mDownloaded = 0;
        mFileLength = connection.getContentLength();
        strLastModified = connection.getHeaderField("Last-Modified");
        Map<String, List<String>> map = connection.getHeaderFields();

        // Setup streams and buffers.
        int chunk = 131072;
        input = new BufferedInputStream(connection.getInputStream(), chunk);
        outFile = new RandomAccessFile(fdest, "rw");
        outFile.seek(seek);
        
        byte data[] = new byte[chunk];
        LogProgress.initProgress(100);
        long i=0;
        // Download file.
        for (int count=0; (count=input.read(data, 0, chunk)) != -1; i++) { 
            outFile.write(data, 0, count);
            mDownloaded += count;
            
            LogProgress.updateProgressValue((int) (mDownloaded * 100 / mFileLength));
            if (mDownloaded >= mFileLength)
                break;
            if (canceled) break;
        }
        // Close streams.
        outFile.close();
        input.close();
        return mDownloaded;
	}
	catch (IOException ioe) {
		try {
			outFile.close();
		} catch (Exception ex1) {}
		try {
			input.close();
		} catch (Exception ex2) {}
		if (canceled) throw new IOException("Job canceled");
		throw ioe;
	}
}
 
Example 19
Source Project: netbeans   File: WebServerTest.java    License: Apache License 2.0 4 votes vote down vote up
private void assertMimetype(String url, String mimetype) throws Exception {
    URLConnection is = new URL(url).openConnection();
    is.getInputStream().close();
    String resultMimeType = is.getHeaderField("Content-Type");
    assertEquals(mimetype, resultMimeType);
}
 
Example 20
@Messages({"# {0} - server location", "# {1} - user name", "APITokenConnectionAuthenticator.password_description=API token for {1} on {0}"})
@org.netbeans.api.annotations.common.SuppressWarnings("DM_DEFAULT_ENCODING")
@Override public URLConnection forbidden(URLConnection conn, URL home) {
    String version = conn.getHeaderField("X-Jenkins");
    if (version == null) {
        if (conn.getHeaderField("X-Hudson") == null) {
            LOG.log(Level.FINE, "neither Hudson nor Jenkins headers on {0}, assuming might be Jenkins", home);
        } else {
            LOG.log(Level.FINE, "disabled on non-Jenkins server {0}", home);
            return null;
        }
    } else if (new HudsonVersion(version).compareTo(new HudsonVersion("1.426")) < 0) {
        LOG.log(Level.FINE, "disabled on old ({0}) Jenkins server {1}", new Object[] {version, home});
        return null;
    } else {
        LOG.log(Level.FINE, "enabled on {0}", home);
    }
    APITokenConnectionAuthenticator panel = new APITokenConnectionAuthenticator();
    String server = HudsonManager.simplifyServerLocation(home.toString(), true);
    String key = "tok." + server;
    String username = FormLogin.loginPrefs().get(server, null);
    if (username != null) {
        panel.userField.setText(username);
        char[] savedToken = Keyring.read(key);
        if (savedToken != null) {
            panel.tokField.setText(new String(savedToken));
        }
    }
    panel.locationField.setText(home.toString());
    DialogDescriptor dd = new DialogDescriptor(panel, Bundle.FormLogin_log_in());
    if (DialogDisplayer.getDefault().notify(dd) != NotifyDescriptor.OK_OPTION) {
        return null;
    }
    username = panel.userField.getText();
    LOG.log(Level.FINE, "trying token for {0} on {1}", new Object[] {username, home});
    FormLogin.loginPrefs().put(server, username);
    String token = new String(panel.tokField.getPassword());
    panel.tokField.setText("");
    Keyring.save(key, token.toCharArray(), Bundle.APITokenConnectionAuthenticator_password_description(home, username));
    BASIC_AUTH.put(home.toString(), new Base64(0).encodeToString((username + ':' + token).getBytes()).trim());
    try {
        return conn.getURL().openConnection();
    } catch (IOException x) {
        LOG.log(Level.FINE, null, x);
        return null;
    }
}