本文整理汇总了Java中java.net.HttpURLConnection.getHeaderField方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.getHeaderField方法的具体用法?Java HttpURLConnection.getHeaderField怎么用?Java HttpURLConnection.getHeaderField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.getHeaderField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: requestTicketGrantingTicket
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private String requestTicketGrantingTicket(final String username, final String password) {
HttpURLConnection connection = null;
try {
connection = HttpUtils.openPostConnection(new URL(this.casRestUrl));
final String payload = HttpUtils.encodeQueryParam(Pac4jConstants.USERNAME, username)
+ "&" + HttpUtils.encodeQueryParam(Pac4jConstants.PASSWORD, password);
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), HttpConstants.UTF8_ENCODING));
out.write(payload);
out.close();
final String locationHeader = connection.getHeaderField("location");
final int responseCode = connection.getResponseCode();
if (locationHeader != null && responseCode == HttpConstants.CREATED) {
return locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
}
throw new TechnicalException("Ticket granting ticket request failed: " + locationHeader + " " + responseCode +
HttpUtils.buildHttpErrorMessage(connection));
} catch (final IOException e) {
throw new TechnicalException(e);
} finally {
HttpUtils.closeConnection(connection);
}
}
示例2: getFileName
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 获取文件名
*/
private String getFileName(HttpURLConnection conn) {
String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);
if (filename == null || "".equals(filename.trim())) {//如果获取不到文件名称
for (int i = 0; ; i++) {
String mine = conn.getHeaderField(i);
if (mine == null)
break;
if ("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())) {
Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
if (m.find())
return m.group(1);
}
}
filename = UUID.randomUUID() + ".tmp";//默认取一个文件名
}
if (filename.indexOf("?") != -1) {
filename = filename.substring(0, filename.lastIndexOf("?"));
}
return filename;
}
示例3: asyncCheckLatestAppVersion
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void asyncCheckLatestAppVersion() {
try {
URL url = new URL(getString(R.string.latest_release_url));
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
String secondUrl = String.valueOf(secondURL);
String latestVersion = Uri.parse(secondUrl).getLastPathSegment();
Log.d("GM/updateUrl", secondUrl);
if (getActivity() != null) {
String checkUrl = getString(R.string.current_release_url_prefix) + BuildConfig.VERSION_NAME;
if (secondUrl.equals(checkUrl)) {
versionSummary = BuildConfig.VERSION_NAME + " " +
getString(R.string.version_summary_latest);
} else {
versionSummary = BuildConfig.VERSION_NAME + " " +
"(" + getString(R.string.version_summary_changed_latest) + latestVersion + ")";
latestVersionUrl = secondUrl;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
versionPref.setSummary(versionSummary);
Log.d("GM/versionChecked", versionSummary);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
示例4: load
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public MasterTemplateLoader load()
{
try
{
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("-Xcloudnet-user", simpledUser.getUserName());
urlConnection.setRequestProperty("-Xcloudnet-token", simpledUser.getApiToken());
urlConnection.setRequestProperty("-Xmessage", customName != null ? "custom" : "template");
urlConnection.setRequestProperty("-Xvalue",customName != null ? customName : new Document("template", template.getName()).append("group", group).convertToJsonString());
urlConnection.setUseCaches(false);
urlConnection.connect();
if(urlConnection.getHeaderField("-Xresponse") == null)
{
Files.copy(urlConnection.getInputStream(), Paths.get(dest));
}
urlConnection.disconnect();
} catch (IOException e)
{
e.printStackTrace();
}
return this;
}
示例5: getChallengeHeader
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Get the digest challenge header by connecting to the resource
* with no credentials.
*/
public static String getChallengeHeader(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoOutput(true);
conn.getOutputStream().close();
try {
conn.getInputStream().close();
} catch (IOException ex) {
if (401 == conn.getResponseCode()) {
// we expect a 401-unauthorized response with the
// WWW-Authenticate header to create the request with the
// necessary auth data
String hdr = conn.getHeaderField("WWW-Authenticate");
if (hdr != null && !"".equals(hdr)) {
return hdr;
}
} else if (400 == conn.getResponseCode()) {
// 400 usually means that auth is disabled on the Fabric node
throw new IOException("Fabric returns status 400. If authentication is disabled on the Fabric node, "
+ "omit the `fabricUsername' and `fabricPassword' properties from your connection.");
} else {
throw ex;
}
}
return null;
}
示例6: parseHttpResponse
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void parseHttpResponse(HttpURLConnection httpConnection, boolean isAcceptRanges)
throws DownloadException {
final long length;
String contentLength = httpConnection.getHeaderField("Content-Length");
if (TextUtils.isEmpty(contentLength) || contentLength.equals("0") || contentLength
.equals("-1")) {
length = httpConnection.getContentLength();
} else {
length = Long.parseLong(contentLength);
}
if (length <= 0) {
throw new DownloadException(DownloadException.EXCEPTION_FILE_SIZE_ZERO, "length <= 0");
}
checkIfPause();
onGetFileInfoListener.onSuccess(length, isAcceptRanges);
}
示例7: testPersistentCookie
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test
public void testPersistentCookie() throws IOException {
try {
startServer(false);
} catch (Exception e) {
// Auto-generated catch block
e.printStackTrace();
}
URL base = new URL("http://" + NetUtils.getHostPortString(server
.getConnectorAddress(0)));
HttpURLConnection conn = (HttpURLConnection) new URL(base,
"/echo").openConnection();
String header = conn.getHeaderField("Set-Cookie");
List<HttpCookie> cookies = HttpCookie.parse(header);
Assert.assertTrue(!cookies.isEmpty());
Log.info(header);
Assert.assertTrue(header.contains("; Expires="));
Assert.assertTrue("token".equals(cookies.get(0).getValue()));
}
示例8: readRaw
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Reads the raw response from a server.
* @param connection the HttpURLConnection to read the raw response from.
* @return The raw response from the server.
* @throws IOException if an IOException occurs.
*/
public static synchronized String readRaw(HttpURLConnection connection) throws IOException
{
connection.connect();
Map<String,List<String>> headMap = connection.getHeaderFields();
String raw = "";
//A status line which includes the status code and reason message
// (e.g., HTTP/1.1 200 OK).
raw += connection.getHeaderField(null)+'\n';
//Response header fields
for(String head : headMap.keySet())
{
if(head==null)
continue;
raw += head + ": ";
List<String> vals = headMap.get(head);
//Response header field values (e.g., Content-Type: text/html).
for(String v : vals)
raw += v;
raw += '\n';
}
//An empty line.
raw += '\n';
//An optional message body.
raw += read(connection);
return raw;
}
示例9: create
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* <b>CREATE</b>
*
* curl -i -X PUT "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=CREATE
* [&overwrite=<true|false>][&blocksize=<LONG>][&replication=<SHORT>]
* [&permission=<OCTAL>][&buffersize=<INT>]"
*
* @param path
* @param is
* @return
* @throws MalformedURLException
* @throws IOException
* @throws AuthenticationException
*/
public String create(String path, InputStream is)
throws MalformedURLException, IOException, AuthenticationException {
String resp = null;
ensureValidToken();
String redirectUrl = null;
HttpURLConnection conn = authenticatedURL
.openConnection(
new URL(new URL(httpfsUrl), MessageFormat.format(
"/webhdfs/v1/{0}?op=CREATE",
URLUtil.encodePath(path))), token);
conn.setRequestMethod("PUT");
conn.setInstanceFollowRedirects(false);
conn.connect();
logger.info("Location:" + conn.getHeaderField("Location"));
System.out.println("Location:" + conn.getHeaderField("Location"));
resp = result(conn, true);
if (conn.getResponseCode() == 307)
redirectUrl = conn.getHeaderField("Location");
conn.disconnect();
if (redirectUrl != null) {
conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/octet-stream");
// conn.setRequestProperty("Transfer-Encoding", "chunked");
final int _SIZE = is.available();
conn.setRequestProperty("Content-Length", "" + _SIZE);
conn.setFixedLengthStreamingMode(_SIZE);
conn.connect();
OutputStream os = conn.getOutputStream();
copy(is, os);
// Util.copyStream(is, os);
is.close();
os.close();
resp = result(conn, false);
conn.disconnect();
}
return resp;
}
示例10: checkForRedirect
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static String checkForRedirect(String url) {
try {
HttpURLConnection con = (HttpURLConnection) new URL( url ).openConnection();
if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
url = con.getHeaderField("Location");
}
} catch(IOException e) {
e.printStackTrace();
}
return url;
}
示例11: append
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* curl -i -X POST
* "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=APPEND[&buffersize=<INT>]"
*
* @param path
* @param is
* @return
* @throws MalformedURLException
* @throws IOException
* @throws AuthenticationException
*/
public String append(String path, InputStream is)
throws IOException, AuthenticationException {
String resp = null;
ensureValidToken();
String spec = MessageFormat.format(
"/webhdfs/v1/{0}?op=APPEND&user.name={1}",
URLUtil.encodePath(path), this.principal);
String redirectUrl = null;
HttpURLConnection conn = authenticatedURL.openConnection(new URL(
new URL(httpfsUrl), spec), token);
conn.setRequestMethod("POST");
conn.setInstanceFollowRedirects(false);
conn.connect();
logger.info("Location:" + conn.getHeaderField("Location"));
resp = result(conn, true);
if (conn.getResponseCode() == 307)
redirectUrl = conn.getHeaderField("Location");
conn.disconnect();
if (redirectUrl != null) {
conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/octet-stream");
// conn.setRequestProperty("Transfer-Encoding", "chunked");
final int _SIZE = is.available();
conn.setRequestProperty("Content-Length", "" + _SIZE);
conn.setFixedLengthStreamingMode(_SIZE);
conn.connect();
OutputStream os = conn.getOutputStream();
copy(is, os);
// Util.copyStream(is, os);
is.close();
os.close();
resp = result(conn, true);
conn.disconnect();
}
return resp;
}
示例12: getLocation
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private String getLocation(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setInstanceFollowRedirects(false);
if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 400)
throw new IOException("Error " + connection.getResponseCode() + " at " + url);
return connection.getHeaderField("location");
}
示例13: parseOkHeaders
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Process response headers from first server response. This derives its
* filename, size, and ETag.
*/
private void parseOkHeaders(HttpURLConnection conn) throws StopRequestException {
if (mInfoDelta.mFileName == null) {
final String contentDisposition = conn.getHeaderField("Content-Disposition");
final String contentLocation = conn.getHeaderField("Content-Location");
try {
mInfoDelta.mFileName = Helpers.generateSaveFile(mContext, mInfoDelta.mUri,
mInfo.mHint, contentDisposition, contentLocation, mInfoDelta.mMimeType,
mInfo.mDestination);
} catch (IOException e) {
throw new StopRequestException(
STATUS_FILE_ERROR, "Failed to generate filename: " + e);
}
}
if (mInfoDelta.mMimeType == null) {
mInfoDelta.mMimeType = StorageUtils.normalizeMimeType(conn.getContentType());
}
final String transferEncoding = conn.getHeaderField("Transfer-Encoding");
if (transferEncoding == null) {
mInfoDelta.mTotalBytes = getHeaderFieldLong(conn, "Content-Length", -1);
} else {
mInfoDelta.mTotalBytes = -1;
}
mInfoDelta.mETag = conn.getHeaderField("ETag");
mInfoDelta.writeToDatabaseOrThrow();
// Check connectivity again now that we know the total size
checkConnectivity();
}
示例14: getRedirectUrl
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private String getRedirectUrl(String urlString) {
String domain = getBaseDomain(urlString);
if (isShortenUrl(domain)) {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
String redirectUrl = connection.getHeaderField("Location");
if (redirectUrl == null) {
List<String> entrySet = connection.getHeaderFields().get("Refresh");
if (entrySet != null) {
for (String refreshUrl : entrySet) {
redirectUrl = refreshUrl.replace("1;URL=", "");
}
}
}
if (redirectUrl != null) {
urlString = getRedirectUrl(redirectUrl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return urlString;
}
示例15: getMimeType
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public String getMimeType(Uri uri) {
switch (getUriType(uri)) {
case URI_TYPE_FILE:
case URI_TYPE_ASSET:
return getMimeTypeFromPath(uri.getPath());
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE:
return contentResolver.getType(uri);
case URI_TYPE_DATA: {
return getDataUriMimeType(uri);
}
case URI_TYPE_HTTP:
case URI_TYPE_HTTPS: {
try {
HttpURLConnection conn = (HttpURLConnection)new URL(uri.toString()).openConnection();
conn.setDoInput(false);
conn.setRequestMethod("HEAD");
String mimeType = conn.getHeaderField("Content-Type");
if (mimeType != null) {
mimeType = mimeType.split(";")[0];
}
return mimeType;
} catch (IOException e) {
}
}
}
return null;
}