当前位置: 首页>>代码示例>>Java>>正文


Java HttpURLConnection.getHeaderField方法代码示例

本文整理汇总了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);
    }
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:26,代码来源:CasRestAuthenticator.java

示例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;
}
 
开发者ID:LingjuAI,项目名称:AssistantBySDK,代码行数:24,代码来源:DownloadTask.java

示例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();
    }
}
 
开发者ID:xRahul,项目名称:GroupingMessages,代码行数:32,代码来源:SettingsFragment.java

示例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;
}
 
开发者ID:Dytanic,项目名称:CloudNet,代码行数:25,代码来源:MasterTemplateLoader.java

示例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;
}
 
开发者ID:JuanJoseFJ,项目名称:ProyectoPacientes,代码行数:30,代码来源:DigestAuthentication.java

示例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);
}
 
开发者ID:lifengsofts,项目名称:AndroidDownloader,代码行数:21,代码来源:GetFileInfoTask.java

示例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()));
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:22,代码来源:TestAuthenticationSessionCookie.java

示例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;
}
 
开发者ID:Jenna3715,项目名称:ChatBot,代码行数:33,代码来源:WebRequest.java

示例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;
}
 
开发者ID:Transwarp-DE,项目名称:Transwarp-Sample-Code,代码行数:59,代码来源:KerberosWebHDFSConnection2.java

示例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;
}
 
开发者ID:iedadata,项目名称:geomapapp,代码行数:12,代码来源:URLFactory.java

示例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;
}
 
开发者ID:Transwarp-DE,项目名称:Transwarp-Sample-Code,代码行数:54,代码来源:PseudoWebHDFSConnection.java

示例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");
}
 
开发者ID:Franckyi,项目名称:CMPDL,代码行数:8,代码来源:CustomTask.java

示例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();
}
 
开发者ID:redleaf2002,项目名称:downloadmanager,代码行数:38,代码来源:DownloadThread.java

示例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;
}
 
开发者ID:collaction,项目名称:content-farm-blocker-android,代码行数:29,代码来源:DetectorActivity.java

示例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;
}
 
开发者ID:SUTFutureCoder,项目名称:localcloud_fe,代码行数:30,代码来源:CordovaResourceApi.java


注:本文中的java.net.HttpURLConnection.getHeaderField方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。