當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。