當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpHead.setHeader方法代碼示例

本文整理匯總了Java中org.apache.http.client.methods.HttpHead.setHeader方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpHead.setHeader方法的具體用法?Java HttpHead.setHeader怎麽用?Java HttpHead.setHeader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.http.client.methods.HttpHead的用法示例。


在下文中一共展示了HttpHead.setHeader方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: head

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
/**
 * HEAD request
 * @param url URL to make request to
 * @param headers Extra headers to add. Even-numbered elements will be treated as header names, and odd-numbered elements will be treated as header values.
 * @return Response status code.
 * @throws java.io.IOException
 * @throws java.security.GeneralSecurityException
 */
public static String head(String url, String... headers) throws IOException, GeneralSecurityException {
    try (CloseableHttpClient client = getClient()) {
        HttpHead request = new HttpHead(url);
        // Set request headers
        if(headers != null) {
            for(int i = 0; i < headers.length; i+=2) {
                request.setHeader(headers[i], headers[i+1]);
            }
        }
        // Execute the request
        try (CloseableHttpResponse response = client.execute(request)) {
            // Parse the response
            int statusCode = response.getStatusLine().getStatusCode();
            
            // Package it up for MATLAB.
            String returnVal = Integer.toString(statusCode);
            return returnVal;
        }
    }
}
 
開發者ID:psexton,項目名稱:missing-http,代碼行數:29,代碼來源:MatlabShim.java

示例2: generateHttpRequest

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
/**
 * 構造HttpHead
 */
protected HttpUriRequest generateHttpRequest() {
    String resource = httpTool.generateCanonicalizedResource("/"
            + bucketName + "/" + objectKey);
    String requestUri = OSS_END_POINT + resource;
    HttpHead httpHead = new HttpHead(requestUri);

    String dateStr = Helper.getGMTDate();
    String authorization = OSSHttpTool
            .generateAuthorization(accessId, accessKey,
                    httpMethod.toString(), "", "", dateStr, "", resource);

    httpHead.setHeader(AUTHORIZATION, authorization);
    httpHead.setHeader(DATE, dateStr);
    httpHead.setHeader(HOST, OSS_HOST);

    OSSHttpTool.addHttpRequestHeader(httpHead, IF_MODIFIED_SINCE,
            Helper.getGMTDate(modifiedSince));
    OSSHttpTool.addHttpRequestHeader(httpHead, IF_UNMODIFIED_SINCE,
            Helper.getGMTDate(unModifiedSince));
    OSSHttpTool.addHttpRequestHeader(httpHead, IF_MATCH, expectedETag);
    OSSHttpTool.addHttpRequestHeader(httpHead, IF_NONE_MATCH,
            unexpectedETag);

    return httpHead;
}
 
開發者ID:wiscserc,項目名稱:aliyunoss,代碼行數:29,代碼來源:HeadObjectTask.java

示例3: testHeadToGetSwitch

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
@Test
public void testHeadToGetSwitch() throws Exception {
    HttpHead head = new HttpHead(getHttpURl("/hello/html"));
    // When checking the content length, we must disable the compression:
    head.setHeader(HeaderNames.ACCEPT_ENCODING, "identity");
    HttpResponse<String> response;
    try {
        org.apache.http.HttpResponse resp = ClientFactory.getHttpClient().execute(head);
        response = new HttpResponse<>(resp, String.class);
    } finally {
        head.releaseConnection();
    }

    assertThat(response.code()).isEqualTo(OK);
    assertThat(response.contentType()).isEqualTo(MimeTypes.HTML);
    System.out.println(response.headers());
    assertThat(Integer.valueOf(response.header(CONTENT_LENGTH))).isEqualTo(20);
}
 
開發者ID:wisdom-framework,項目名稱:wisdom,代碼行數:19,代碼來源:HeadIT.java

示例4: testHead

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
public void testHead(String resource, String host) throws ClientProtocolException, IOException {
	CloseableHttpClient httpclient = HttpClients.createDefault();
	HttpHead httpMethod = new HttpHead(url + resource);
	if (host != null && !host.trim().isEmpty())
		httpMethod.setHeader("Host", host);
	HttpResponse response = httpclient.execute(httpMethod);
	System.out.println(httpMethod);
	System.out.println(response.toString());
	EntityUtils.consume(response.getEntity());
	System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
	httpclient.close();
}
 
開發者ID:regestaexe,項目名稱:bygle-ldp,代碼行數:13,代碼來源:HttpTest.java

示例5: setPostsAsRead

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
/**
 * {@inheritDoc}
 */
public boolean setPostsAsRead(Topic topic, int pageNumber) throws DataRetrieverException
{
	String url = POSTS_URL.replaceFirst("\\{\\$cat\\}", topic.getCategory().getRealId())
	.replaceFirst("\\{\\$topic\\}", String.valueOf(topic.getId()))
	.replaceFirst("\\{\\$page\\}", String.valueOf(pageNumber));
	
	Log.d(HFR4droidApplication.TAG, "Retrieving " + url);
	try
	{
		URI uri = new URI(url);
		HttpHead method = new HttpHead(uri);
		method.setHeader("User-Agent", HFR4droidApplication.getUserAgent());
		HttpContext httpContext = new BasicHttpContext();
		if (auth != null && auth.getCookies() != null && fakeCs != null)
		{
			httpContext.setAttribute(ClientContext.COOKIE_STORE, auth.getCookies());
		}
		
		HttpResponse response = httpClientHelper.getHttpClient().execute(method, httpContext);
		Log.d(HFR4droidApplication.TAG, "Status : " + response.getStatusLine().getStatusCode() + ", " + response.getStatusLine().getReasonPhrase());
		return response.getStatusLine().getStatusCode() == 200;
	}
	catch (Exception e)
	{
		throw new DataRetrieverException(context.getString(R.string.error_dr_topics), e);
	}
}
 
開發者ID:Draluy,項目名稱:HFRFirefoxOS,代碼行數:31,代碼來源:HFRDataRetriever.java

示例6: headResponsObject

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
public static Map<String, String> headResponsObject(String urlOffset, OAuth2AccessToken oauth2AccessToken, Map<String, String> headers, int expect) throws CloudFoundryException {
		HttpHead request = new HttpHead();
		try {
			request.setURI(new URL(oauth2AccessToken.getString(OAuth2AccessToken.Fields.target.name())+urlOffset).toURI());
		} catch (MalformedURLException | JSONException | URISyntaxException e) {
			e.printStackTrace();
			throw new CloudFoundryException(HttpStatus.SC_BAD_REQUEST,e.getMessage());
		} 
		request.setHeader("Content-Type", "application/x-www-form-urlencoded");
		request.setHeader("Accept", "application/json;charset=utf-8");
		request.setHeader("Authorization", "bearer "+oauth2AccessToken.getString(OAuth2AccessToken.Fields.access_token.name()));

		if (headers!=null) {
			for (String key : headers.keySet()) {
				request.setHeader(key, headers.get(key));			
			}
		}
		try {
			HttpResponse response = HttpClientFactory.getThreadSafeClient().execute(request);	
			int returnCode = response.getStatusLine().getStatusCode();
			if ((returnCode!=HttpStatus.SC_OK)&&(returnCode!=HttpStatus.SC_PARTIAL_CONTENT)) {
				throw new CloudFoundryException(response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase());
			}
			// copy the headers into the response object in case caller needs them, some silly
			// api contract thought this is a good way to communicate information.
			Header[] rheaders = response.getAllHeaders();
			headers = new HashMap<String,String>();
			for (int i = 0; i < rheaders.length; i++) {
				headers.put(rheaders[i].getName(), rheaders[i].getValue());
			}
			return headers;
		}
		catch (Throwable t) {
//			t.printStackTrace();
			throw new CloudFoundryException(HttpStatus.SC_BAD_REQUEST,t.getMessage());
		}
	}
 
開發者ID:stephen-kruger,項目名稱:cloudfoundry-liteclient-lib,代碼行數:38,代碼來源:ResponseObject.java

示例7: getWorkspacePermissions

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
private String getWorkspacePermissions(User user, Workspace workspace) throws Exception {

        if (!isTokenActive()) {
            login();
        }

        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };

        SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 5000, sf));
        ClientConnectionManager ccm = new SingleClientConnManager(registry);

        HttpClient httpClient = new DefaultHttpClient(ccm);

        String url = this.storageUrl + "/" + workspace.getSwiftContainer();

        try {

            HttpHead request = new HttpHead(url);
            request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

            HttpResponse response = httpClient.execute(request);

            SwiftResponse swiftResponse = new SwiftResponse(response);

            if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                throw new UnauthorizedException("404 User unauthorized");
            }

            if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
                throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
            }

            // We suppose there are the same permissions for read and write
            Header containerWriteHeader = swiftResponse.getResponseHeader(SwiftResponse.X_CONTAINER_WRITE);

            if (containerWriteHeader == null) {
                return "";
            }

            return containerWriteHeader.getValue();

        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
 
開發者ID:stacksync,項目名稱:sync-service,代碼行數:53,代碼來源:SwiftManagerHTTPS.java

示例8: getWorkspacePermissions

import org.apache.http.client.methods.HttpHead; //導入方法依賴的package包/類
private String getWorkspacePermissions(User user, Workspace workspace) throws Exception {

        if (!isTokenActive()) {
            login();
        }

        HttpClient httpClient = new DefaultHttpClient();

        String url = this.storageUrl + "/" + workspace.getSwiftContainer();

        try {

            HttpHead request = new HttpHead(url);
            request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

            HttpResponse response = httpClient.execute(request);

            SwiftResponse swiftResponse = new SwiftResponse(response);

            if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                throw new UnauthorizedException("404 User unauthorized");
            }

            if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
                throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
            }

            // We suppose there are the same permissions for read and write
            Header containerWriteHeader = swiftResponse.getResponseHeader(SwiftResponse.X_CONTAINER_WRITE);

            if (containerWriteHeader == null) {
                return "";
            }

            return containerWriteHeader.getValue();

        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
 
開發者ID:stacksync,項目名稱:sync-service,代碼行數:41,代碼來源:SwiftManager.java


注:本文中的org.apache.http.client.methods.HttpHead.setHeader方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。