本文整理汇总了Java中org.apache.http.Header类的典型用法代码示例。如果您正苦于以下问题:Java Header类的具体用法?Java Header怎么用?Java Header使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Header类属于org.apache.http包,在下文中一共展示了Header类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendResponseMessage
import org.apache.http.Header; //导入依赖的package包/类
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
if (!Thread.currentThread().isInterrupted()) {
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
//already finished
if (!Thread.currentThread().isInterrupted())
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
} else if (status.getStatusCode() >= 300) {
if (!Thread.currentThread().isInterrupted())
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
} else {
if (!Thread.currentThread().isInterrupted()) {
Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
if (header == null) {
append = false;
current = 0;
} else {
Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
}
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity()));
}
}
}
}
示例2: logResponse
import org.apache.http.Header; //导入依赖的package包/类
private LogInstance logResponse( LogInstance logInstance, HttpResponse response, String respBody ) {
if( response != null ) {
logInstance.setRespHttpStatus( response.getStatusLine().getStatusCode() );
// log request headers and body?
for( Header header : response.getAllHeaders() ) {
if( logLevel == LogLevel.TRACE || header.getName().toLowerCase().equals( "x-gateway-site-id" ) || header.getName().toLowerCase().equals( "x-request-uuid" ) ) {
logInstance.addRespHeader( header.getName(), header.getValue() );
}
}
if( logLevel == LogLevel.TRACE ) {
if( respBody != null ) {
String logRespBody;
if( respBody.length() > REQUEST_AND_RESPONSE_BODY_LOG_MAX_LENGTH ) {
logRespBody = respBody.substring( 0, REQUEST_AND_RESPONSE_BODY_LOG_MAX_LENGTH ) + "...response body truncated...";
}
else logRespBody = respBody;
logInstance.setRespBody( logRespBody );
}
}
}
return logInstance;
}
示例3: initPoolingHttpClientManager
import org.apache.http.Header; //导入依赖的package包/类
private void initPoolingHttpClientManager () {
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(MAX_CONNECTION);
connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);
final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT);
final RequestConfig requestConfig = requestConfigBuilder.build();
HashSet<Header> defaultHeaders = new HashSet<Header>();
defaultHeaders.add(new BasicHeader(HttpHeaders.PRAGMA, "no-cache"));
defaultHeaders.add(new BasicHeader(HttpHeaders.CACHE_CONTROL, "no-cache"));
final HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(defaultHeaders).disableAuthCaching().disableContentCompression();
this.httpClient = httpClientBuilder.setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
}
示例4: uploadTarZip
import org.apache.http.Header; //导入依赖的package包/类
private void uploadTarZip( String token, String headerLocationUrl, String digestTgz, String filePath ) throws TenableIoException {
Header[] headersArray = new Header[2];
headersArray[0] = getTokenHeader( token );
headersArray[1] = new BasicHeader( "Content-Type", "application/vnd.docker.image.rootfs.diff.tar.gzip" );
try {
byte[] fileBinary = Files.readAllBytes( Paths.get( filePath ) );
URIBuilder uploadUrl = new URIBuilder( headerLocationUrl );
uploadUrl.addParameter( "digest", digestTgz );
AsyncHttpService asyncHttpService = new AsyncHttpService( null );
HttpFuture httpFuture = asyncHttpService.doPut( uploadUrl.build(), ContentType.DEFAULT_BINARY, fileBinary, headersArray );
httpFuture.get();
} catch ( Exception e ) {
throw new TenableIoException( TenableIoErrorCode.Generic, "Error while uploading tar zip.", e );
}
}
示例5: createResponse
import org.apache.http.Header; //导入依赖的package包/类
/**
* Creates and initializes an HttpResponse object suitable to be passed to an HTTP response
* handler object.
*
* @param method The HTTP method that was invoked to get the response.
* @param context The HTTP context associated with the request and response.
* @return The new, initialized HttpResponse object ready to be passed to an HTTP response
* handler object.
* @throws IOException If there were any problems getting any response information from the
* HttpClient method object.
*/
private HttpResponse createResponse(HttpRequestBase method,
org.apache.http.HttpResponse apacheHttpResponse,
HttpContext context) throws IOException {
HttpResponse httpResponse = new HttpResponse(request, method, context);
if (apacheHttpResponse.getEntity() != null) {
httpResponse.setContent(apacheHttpResponse.getEntity().getContent());
}
httpResponse.setStatusCode(apacheHttpResponse.getStatusLine().getStatusCode());
httpResponse.setStatusText(apacheHttpResponse.getStatusLine().getReasonPhrase());
for (Header header : apacheHttpResponse.getAllHeaders()) {
httpResponse.addHeader(header.getName(), header.getValue());
}
return httpResponse;
}
示例6: sendResponseMessage
import org.apache.http.Header; //导入依赖的package包/类
@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
StatusLine status = response.getStatusLine();
Header[] contentTypeHeaders = response.getHeaders("Content-Type");
if (contentTypeHeaders.length != 1) {
//malformed/ambiguous HTTP Header, ABORT!
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
return;
}
Header contentTypeHeader = contentTypeHeaders[0];
boolean foundAllowedContentType = false;
for (String anAllowedContentType : getAllowedContentTypes()) {
try {
if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
foundAllowedContentType = true;
}
} catch (PatternSyntaxException e) {
}
}
if (!foundAllowedContentType) {
//Content-Type not in allowed list, ABORT!
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
return;
}
super.sendResponseMessage(response);
}
示例7: authenticate
import org.apache.http.Header; //导入依赖的package包/类
/**
* Produces basic authorization header for the given set of {@link Credentials}.
*
* @param credentials The set of credentials to be used for authentication
* @param request The request being authenticated
* @throws InvalidCredentialsException if authentication credentials are not
* valid or not applicable for this authentication scheme
* @throws AuthenticationException if authorization string cannot
* be generated due to an authentication failure
*
* @return a basic authorization string
*/
@Override
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
String charset = AuthParams.getCredentialCharset(request.getParams());
return authenticate(credentials, charset, isProxy());
}
示例8: sendResponseMessage
import org.apache.http.Header; //导入依赖的package包/类
protected void sendResponseMessage(HttpResponse response) {
super.sendResponseMessage(response);
Header[] headers = response.getHeaders("Set-Cookie");
if (headers != null && headers.length > 0) {
CookieSyncManager.createInstance(LemallPlatform.getInstance().getContext()).sync();
CookieManager instance = CookieManager.getInstance();
instance.setAcceptCookie(true);
instance.removeSessionCookie();
String mm = "";
for (Header header : headers) {
String[] split = header.toString().split("Set-Cookie:");
EALogger.i("游客登录", "split[1]===>" + split[1]);
instance.setCookie(Constants.GUESTLOGIN, split[1]);
int index = split[1].indexOf(";");
if (TextUtils.isEmpty(mm)) {
mm = split[1].substring(index + 1);
EALogger.i("正式登录", "mm===>" + mm);
}
}
EALogger.i("游客登录", "split[11]===>COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
instance.setCookie(Constants.GUESTLOGIN, "COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
instance.setCookie(Constants.THIRDLOGIN, "COOKIE_APP_ID=" + LemallPlatform.getInstance().getmAppInfo().getId() + ";" + mm);
CookieSyncManager.getInstance().sync();
this.val$iLetvBrideg.reLoadWebUrl();
}
}
示例9: MatrixHttpContentResult
import org.apache.http.Header; //导入依赖的package包/类
public MatrixHttpContentResult(CloseableHttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
valid = entity != null && response.getStatusLine().getStatusCode() == 200;
if (entity != null) {
headers = Arrays.asList(response.getAllHeaders());
Header contentTypeHeader = entity.getContentType();
if (contentTypeHeader != null) {
contentType = Optional.of(contentTypeHeader.getValue());
} else {
contentType = Optional.empty();
}
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
entity.writeTo(outStream);
data = outStream.toByteArray();
} else {
headers = new ArrayList<>();
contentType = Optional.empty();
data = new byte[0];
}
}
示例10: getProducts
import org.apache.http.Header; //导入依赖的package包/类
@Override
public DProductDescriptions getProducts(List<Long> productIds) throws DeGiroException {
DProductDescriptions products = null;
ensureLogged();
try {
List<Header> headers = new ArrayList<>(1);
ArrayList<String> productIdStr = new ArrayList<>(productIds.size());
for (Long productId : productIds) {
productIdStr.add(productId + "");
}
DResponse response = comm.getUrlData(session.getConfig().getProductSearchUrl(), "v5/products/info?intAccount=" + session.getClient().getIntAccount() + "&sessionId=" + session.getJSessionId(), productIdStr, headers);
products = gson.fromJson(getResponseData(response), DProductDescriptions.class);
} catch (IOException e) {
throw new DeGiroException("IOException while retrieving product information", e);
}
return products;
}
示例11: onFailure
import org.apache.http.Header; //导入依赖的package包/类
/**
* Fired when a request fails to complete, override to handle in your own code
*
* @param statusCode return HTTP status code
* @param headers return headers, if any
* @param responseBody the response body, if any
* @param error the underlying cause of the failure
*/
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
try {
String response = responseBody == null ? null : new String(responseBody, getCharset());
onFailure(statusCode, headers, error, response);
} catch (UnsupportedEncodingException e) {
onFailure(statusCode, headers, e, null);
}
}
示例12: EsRestClient
import org.apache.http.Header; //导入依赖的package包/类
@Inject
public EsRestClient(JkesProperties jkesProperties) {
SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener();
Header[] defaultHeaders = {new BasicHeader("Content-Type", "application/json")};
String[] urls = jkesProperties.getEsBootstrapServers().split("\\s*,");
HttpHost[] hosts = new HttpHost[urls.length];
for (int i = 0; i < urls.length; i++) {
hosts[i] = HttpHost.create(urls[i]);
}
RestClient restClient = RestClient.builder(hosts)
.setRequestConfigCallback(requestConfigBuilder -> {
return requestConfigBuilder.setConnectTimeout(5000) // default 1s
.setSocketTimeout(60000); // defaults to 30 seconds
}).setHttpClientConfigCallback(httpClientBuilder -> {
return httpClientBuilder.setDefaultIOReactorConfig(
IOReactorConfig.custom().setIoThreadCount(2).build()); // because only used for admin, so not necessary to hold many worker threads
})
.setMaxRetryTimeoutMillis(60000) // defaults to 30 seconds
.setDefaultHeaders(defaultHeaders)
.setFailureListener(sniffOnFailureListener)
.build();
Sniffer sniffer = Sniffer.builder(restClient).build();
sniffOnFailureListener.setSniffer(sniffer);
this.sniffer = sniffer;
this.restClient = restClient;
}
示例13: getHeaders
import org.apache.http.Header; //导入依赖的package包/类
@Override
protected Header[] getHeaders() {
int maxAge = 30 * 86400;
return new Header[]{
new BasicHeader("Cache-Control", "max-age=" + maxAge + ", public"),
new BasicHeader("Expires", expiresDateFormat.format(new Date(System.currentTimeMillis() + maxAge * 1000L)))
};
}
示例14: onSuccess
import org.apache.http.Header; //导入依赖的package包/类
public final void onSuccess(final int statusCode, final Header[] headers, final String
responseString) {
if (statusCode != 204) {
Runnable parser = new Runnable() {
public void run() {
try {
final JSON_TYPE jsonResponse = BaseJsonHttpResponseHandler.this
.parseResponse(responseString, false);
BaseJsonHttpResponseHandler.this.postRunnable(new Runnable() {
public void run() {
BaseJsonHttpResponseHandler.this.onSuccess(statusCode, headers,
responseString, jsonResponse);
}
});
} catch (final Throwable t) {
Log.d(BaseJsonHttpResponseHandler.LOG_TAG, "parseResponse thrown an " +
"problem", t);
BaseJsonHttpResponseHandler.this.postRunnable(new Runnable() {
public void run() {
BaseJsonHttpResponseHandler.this.onFailure(statusCode, headers,
t, responseString, null);
}
});
}
}
};
if (getUseSynchronousMode() || getUsePoolThread()) {
parser.run();
return;
} else {
new Thread(parser).start();
return;
}
}
onSuccess(statusCode, headers, null, null);
}
示例15: getVwdSession
import org.apache.http.Header; //导入依赖的package包/类
private void getVwdSession() throws DeGiroException {
try {
List<Header> headers = new ArrayList<>(1);
headers.add(new BasicHeader("Origin", session.getConfig().getTradingUrl()));
HashMap<String, String> data = new HashMap();
data.put("referrer", "https://trader.degiro.nl");
DResponse response = comm.getUrlData("https://degiro.quotecast.vwdservices.com/CORS", "/request_session?version=1.0.20170315&userToken=" + session.getClient().getId(), data, headers);
HashMap map = gson.fromJson(getResponseData(response), HashMap.class);
session.setVwdSession((String) map.get("sessionId"));
session.setLastVwdSessionUsed(System.currentTimeMillis());
} catch (IOException e) {
throw new DeGiroException("IOException while retrieving vwd session", e);
}
}