java.net.URLConnection#getHeaderField ( )源码实例Demo

下面列出了java.net.URLConnection#getHeaderField ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: droidkit-webrtc   文件: AppRTCClient.java
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();
  }
}
 
源代码2 项目: arthas   文件: DownloadUtils.java
/**
 * 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;
}
 
源代码3 项目: jivejdon   文件: TitleExtractor.java
/**
 * 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;
}
 
源代码4 项目: Android-Carbon-Forum   文件: HttpUtil.java
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;
}
 
源代码5 项目: netcdf-java   文件: ServerVersion.java
/**
 * 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.");
}
 
源代码6 项目: org.hl7.fhir.core   文件: ClientUtils.java
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);
  }
}
 
源代码7 项目: org.hl7.fhir.core   文件: ClientUtils.java
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);
  }
}
 
源代码8 项目: org.hl7.fhir.core   文件: ClientUtils.java
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);
	}
}
 
源代码9 项目: zxingfragmentlib   文件: HttpHelper.java
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";
}
 
源代码10 项目: helidon-build-tools   文件: UpdateMetadata.java
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);
}
 
源代码11 项目: Connect-SDK-Android-Core   文件: SSDPDevice.java
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();
}
 
源代码12 项目: sana.mobile   文件: HttpDispatcher.java
@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);
}
 
源代码13 项目: lizzie   文件: AjaxHttpRequest.java
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();
}
 
源代码14 项目: netbeans   文件: Pump.java
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);
}
 
源代码15 项目: netbeans   文件: NetworkAccess.java
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;
}
 
源代码16 项目: astor   文件: UrlModuleSourceProvider.java
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);
}
 
源代码17 项目: updatefx   文件: UpdateDownloadService.java
@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;
        }
    };
}
 
源代码18 项目: Flashtool   文件: URLDownloader.java
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;
	}
}
 
源代码19 项目: netbeans   文件: WebServerTest.java
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);
}
 
源代码20 项目: netbeans   文件: APITokenConnectionAuthenticator.java
@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;
    }
}