本文整理汇总了Java中java.net.URLConnection.getHeaderField方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.getHeaderField方法的具体用法?Java URLConnection.getHeaderField怎么用?Java URLConnection.getHeaderField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLConnection
的用法示例。
在下文中一共展示了URLConnection.getHeaderField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: checkRedirect
import java.net.URLConnection; //导入方法依赖的package包/类
private static URLConnection checkRedirect(URLConnection conn, int timeout) throws IOException {
if (conn instanceof HttpURLConnection) {
conn.connect();
int code = ((HttpURLConnection) conn).getResponseCode();
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 conn
URL redirectedUrl = new URL(redirUrl);
URLConnection connRedir = redirectedUrl.openConnection();
// XXX is this neede
connRedir.setRequestProperty("User-Agent", "NetBeans"); // NOI18N
connRedir.setConnectTimeout(timeout);
connRedir.setReadTimeout(timeout);
if (connRedir instanceof HttpsURLConnection) {
NetworkAccess.initSSL((HttpsURLConnection) connRedir);
}
return connRedir;
}
}
}
return conn;
}
示例2: createOkBody
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Creates an OkHttp Response.Body containing the supplied information.
*/
private static ResponseBody createOkBody(final URLConnection urlConnection) throws IOException {
if (!urlConnection.getDoInput()) {
return null;
}
final BufferedSource body = Okio.buffer(Okio.source(urlConnection.getInputStream()));
return new ResponseBody() {
@Override public MediaType contentType() {
String contentTypeHeader = urlConnection.getContentType();
return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader);
}
@Override public long contentLength() {
String s = urlConnection.getHeaderField("Content-Length");
return stringToLong(s);
}
@Override public BufferedSource source() {
return body;
}
};
}
示例3: getContentTypeHeader
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* 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;
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: loadHeaders
import java.net.URLConnection; //导入方法依赖的package包/类
private void loadHeaders( URLConnection connection ) {
if (HttpUnitOptions.isLoggingHttpHeaders()) {
System.out.println( "Header:: " + connection.getHeaderField(0) );
}
for (int i = 1; true; i++) {
String headerFieldKey = connection.getHeaderFieldKey( i );
String headerField = connection.getHeaderField(i);
if (headerFieldKey == null || headerField == null) break;
if (HttpUnitOptions.isLoggingHttpHeaders()) {
System.out.println( "Header:: " + headerFieldKey + ": " + headerField );
}
addHeader( headerFieldKey.toUpperCase(), headerField );
}
if (connection.getContentType() != null) {
setContentTypeHeader( connection.getContentType() );
}
}
示例5: downloadBytes
import java.net.URLConnection; //导入方法依赖的package包/类
private static byte[] downloadBytes(URL url)
throws MalformedURLException, IOException {
enableHttpProxy();
URLConnection conn = url.openConnection();
if (conn instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) conn;
int status = httpConn.getResponseCode();
if (isRedirect(status)) {
String location = conn.getHeaderField("Location");
httpConn.disconnect();
return downloadBytes(new URL(location));
}
}
InputStream in = conn.getInputStream();
byte[] respBody = readBytes(in);
in.close();
return respBody;
}
示例6: initPumping
import java.net.URLConnection; //导入方法依赖的package包/类
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);
}
示例7: getEncoding
import java.net.URLConnection; //导入方法依赖的package包/类
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";
}
示例8: upstreamRunning
import java.net.URLConnection; //导入方法依赖的package包/类
private static boolean upstreamRunning() {
try {
URL url = new URL("http://localhost:" + UPSTREAM_SERVICE_PORT + "/health");
URLConnection uc = url.openConnection();
uc.connect();
String status = uc.getHeaderField(0);
return status.contains("200");
} catch (Exception e) {
return false;
}
}
示例9: calculateExpiry
import java.net.URLConnection; //导入方法依赖的package包/类
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);
}
示例10: loadTileMetadata
import java.net.URLConnection; //导入方法依赖的package包/类
protected void loadTileMetadata(Tile tile, URLConnection urlConn) {
String str = urlConn.getHeaderField("X-VE-TILEMETA-CaptureDatesRange");
if (str != null) {
tile.putValue("capture-date", str);
}
str = urlConn.getHeaderField("X-VE-Tile-Info");
if (str != null) {
tile.putValue("tile-info", str);
}
Long lng = urlConn.getExpiration();
if (lng.equals(0L)) {
try {
str = urlConn.getHeaderField("Cache-Control");
if (str != null) {
for (String token: str.split(",")) {
if (token.startsWith("max-age=")) {
lng = Long.parseLong(token.substring(8)) * 1000 +
System.currentTimeMillis();
}
}
}
} catch (NumberFormatException e) {
// ignore malformed Cache-Control headers
if (JMapViewer.debug) {
System.err.println(e.getMessage());
}
}
}
if (!lng.equals(0L)) {
tile.putValue("expires", lng.toString());
}
}
示例11: getEncoding
import java.net.URLConnection; //导入方法依赖的package包/类
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";
}
示例12: calculateExpiry
import java.net.URLConnection; //导入方法依赖的package包/类
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);
}
示例13: getCookieHttpClient
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Get a cookie from Google and place it in a ClosableHttpClient
* @return An instance of CloseableHttpClient that is critical to this Class
* @throws IOException When URL connection is improperly formed
*/
private static CloseableHttpClient getCookieHttpClient() throws IOException {
/*
* Tutorial: http://www.hccp.org/java-net-cookie-how-to.html
*/
URL myUrl = new URL("https://trends.google.com");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();
String headerName = null;
for(int i=1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++)
if(headerName.equals("Set-Cookie"))
cookieString = urlConn.getHeaderField(i);
cookieString = cookieString.substring(0, cookieString.indexOf(";"));
/*
* Tutorial: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html#d5e499
*/
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("Cookie", cookieString);
cookie.setDomain(".google.com");
cookie.setPath("/trends");
cookieStore.addCookie(cookie);
return HttpClients.custom().setDefaultCookieStore(cookieStore).build();
}
示例14: assertMimetype
import java.net.URLConnection; //导入方法依赖的package包/类
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);
}
示例15: forbidden
import java.net.URLConnection; //导入方法依赖的package包/类
@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;
}
}