本文整理了Java中org.apache.http.Header
类的一些代码示例,展示了Header
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Header
类的具体详情如下:
包路径:org.apache.http.Header
类名称:Header
[英]Represents an HTTP header field.
The HTTP header fields follow the same generic format as that given in Section 3.1 of RFC 822. Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive. The field value MAY be preceded by any amount of LWS, though a single SP is preferred.
message-header = field-name ":" [ field-value ]
field-name = token
field-value = *( field-content | LWS )
field-content = <the OCTETs making up the field-value
and consisting of either *TEXT or combinations
of token, separators, and quoted-string>
[中]表示HTTP标头字段。
HTTP头字段遵循RFC 822第3.1节中给出的相同通用格式。每个标题字段由一个名称,后跟一个冒号(“:”)和字段值组成。字段名不区分大小写。字段值前面可以有任意数量的LW,但最好是单个SP。
message-header = field-name ":" [ field-value ]
field-name = token
field-value = *( field-content | LWS )
field-content = <the OCTETs making up the field-value
and consisting of either *TEXT or combinations
of token, separators, and quoted-string>
代码示例来源:origin: rapidoid/rapidoid
private static HttpResp response(HttpResponse response) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter printer = new PrintWriter(baos);
printer.print(response.getStatusLine() + "");
printer.print("\n");
Map<String, String> headers = U.map();
for (Header hdr : response.getAllHeaders()) {
printer.print(hdr.getName());
printer.print(": ");
printer.print(hdr.getValue());
printer.print("\n");
headers.put(hdr.getName(), hdr.getValue());
}
printer.print("\n");
printer.flush();
HttpEntity entity = response.getEntity();
byte[] body = entity != null ? IO.loadBytes(response.getEntity().getContent()) : new byte[0];
baos.write(body);
byte[] raw = baos.toByteArray();
return new HttpResp(raw, response.getStatusLine().getStatusCode(), headers, body);
}
代码示例来源:origin: alibaba/nacos
public static HttpResult httpPostLarge(String url, Map<String, String> headers, String content) {
try {
HttpClientBuilder builder = HttpClients.custom();
builder.setUserAgent(UtilsAndCommons.SERVER_VERSION);
builder.setConnectionTimeToLive(500, TimeUnit.MILLISECONDS);
CloseableHttpClient httpClient = builder.build();
HttpPost httpost = new HttpPost(url);
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(), entry.getValue());
}
httpost.setEntity(new StringEntity(content, ContentType.create("application/json", "UTF-8")));
HttpResponse response = httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
HeaderElement[] headerElements = entity.getContentType().getElements();
String charset = headerElements[0].getParameterByName("charset").getValue();
return new HttpResult(response.getStatusLine().getStatusCode(),
IOUtils.toString(entity.getContent(), charset), Collections.<String, String>emptyMap());
} catch (Exception e) {
return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap());
}
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public HttpHeaders getHeaders() {
if (this.headers == null) {
this.headers = new HttpHeaders();
for (Header header : this.httpResponse.getAllHeaders()) {
this.headers.add(header.getName(), header.getValue());
}
}
return this.headers;
}
代码示例来源:origin: apache/hbase
public String getHeader(String key) {
for (Header header: headers) {
if (header.getName().equalsIgnoreCase(key)) {
return header.getValue();
}
}
return null;
}
代码示例来源:origin: loklak/loklak_server
/**
* Find value of location header from the given HttpResponse
* @param httpResponse
* @return Value of location field if exists, null otherwise
*/
public static String getLocationHeader(CloseableHttpResponse httpResponse) {
for (Header header: httpResponse.getAllHeaders()) {
if (header.getName().equalsIgnoreCase("location")) {
return header.getValue();
}
}
return null;
}
代码示例来源:origin: neo4j/neo4j
@Test
public void shouldForwardHttpAndHost() throws Exception
{
URI rootUri = functionalTestHelper.baseUri();
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( rootUri );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "X-Forwarded-Host", "foobar.com" );
httpget.setHeader( "X-Forwarded-Proto", "http" );
HttpResponse response = httpclient.execute( httpget );
String length = response.getHeaders( "CONTENT-LENGTH" )[0].getValue();
byte[] data = new byte[Integer.valueOf( length )];
response.getEntity().getContent().read( data );
String responseEntityBody = new String( data );
assertTrue( responseEntityBody.contains( "http://foobar.com" ) );
assertFalse( responseEntityBody.contains( "http://localhost" ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
代码示例来源:origin: code4craft/webmagic
protected Page handleResponse(Request request, String charset, HttpResponse httpResponse, Task task) throws IOException {
byte[] bytes = IOUtils.toByteArray(httpResponse.getEntity().getContent());
String contentType = httpResponse.getEntity().getContentType() == null ? "" : httpResponse.getEntity().getContentType().getValue();
Page page = new Page();
page.setBytes(bytes);
if (!request.isBinaryContent()){
if (charset == null) {
charset = getHtmlCharset(contentType, bytes);
}
page.setCharset(charset);
page.setRawText(new String(bytes, charset));
}
page.setUrl(new PlainText(request.getUrl()));
page.setRequest(request);
page.setStatusCode(httpResponse.getStatusLine().getStatusCode());
page.setDownloadSuccess(true);
if (responseHeader) {
page.setHeaders(HttpClientUtils.convertHeaders(httpResponse.getAllHeaders()));
}
return page;
}
代码示例来源:origin: jiangqqlmj/FastDev4Android
try {
encodedUri = new URI(url);
httpGet = new HttpGet(encodedUri);
httpGet = new HttpGet(encodedUrl);
e.printStackTrace();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 4000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
4000);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse != null) {
int httpCode = httpResponse.getStatusLine().getStatusCode();
if (httpCode == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
Header header = httpResponse
.getFirstHeader("Content-Encoding");
if (header != null && header.getValue().equals("gzip")) {
Log.d(TAG_LISTLOGIC, "数据已做gzip压缩...");
Log.d(TAG_LISTLOGIC, "数据无Gzip压缩...");
httpGet.abort();
代码示例来源:origin: liyiorg/weixin-popular
@Override
public DownloadbillResult handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
String str;
if (entity.getContentType().getValue().matches("(?i).*gzip.*")) {
str = StreamUtils.copyToString(new GZIPInputStream(entity.getContent()),
Charset.forName("UTF-8"));
} else {
str = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
if(str.matches(".*<xml>(.*|\\n)+</xml>.*")){
return XMLConverUtil.convertToObject(DownloadbillResult.class,str);
dr.setData(str);
Header headerDigest = response.getFirstHeader("Digest");
if (headerDigest != null) {
String[] hkv = headerDigest.getValue().split("=");
dr.setSign_type(hkv[0]);
dr.setSign(hkv[1]);
代码示例来源:origin: dreamhead/moco
@Override
public void run() throws Exception {
HttpResponse httpResponse = helper.postForResponse(remoteUrl("/targets"),
Jsons.toJson(resource1));
assertThat(httpResponse.getStatusLine().getStatusCode(), is(201));
assertThat(httpResponse.getFirstHeader("Location").getValue(), is("/targets/123"));
}
});
代码示例来源:origin: aws/aws-sdk-java
url += "/?activationRegion=" + activationRegionName;
HttpGet method = new HttpGet(url);
HttpResponse response = client.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
Header[] headers = response.getHeaders("Location");
if (headers.length < 1)
throw new AmazonClientException("Could not fetch activation key, no location header found");
String activationUrl = headers[0].getValue();
String[] parts = activationUrl.split("activationKey=");
代码示例来源:origin: apache/nifi
final HttpGet get = new HttpGet(url);
get.setConfig(requestConfigBuilder.build());
final String lastModified = beforeStateMap.get(LAST_MODIFIED + ":" + url);
if (lastModified != null) {
get.addHeader(HEADER_IF_MODIFIED_SINCE, parseStateValue(lastModified).getValue());
final StopWatch stopWatch = new StopWatch(true);
final HttpResponse response = client.execute(get);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == NOT_MODIFIED) {
logger.info("content not retrieved because server returned HTTP Status Code {}: Not Modified", new Object[]{NOT_MODIFIED});
return;
final String statusExplanation = response.getStatusLine().getReasonPhrase();
flowFile = session.putAttribute(flowFile, CoreAttributes.FILENAME.key(), context.getProperty(FILENAME).evaluateAttributeExpressions().getValue());
flowFile = session.putAttribute(flowFile, this.getClass().getSimpleName().toLowerCase() + ".remote.source", source);
flowFile = session.importFrom(response.getEntity().getContent(), flowFile);
final Header contentTypeHeader = response.getFirstHeader("Content-Type");
if (contentTypeHeader != null) {
final String contentType = contentTypeHeader.getValue();
if (!contentType.trim().isEmpty()) {
flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), contentType.trim());
代码示例来源:origin: Kong/unirest-java
@SuppressWarnings("unchecked")
public HttpResponse(org.apache.http.HttpResponse response, Class<T> responseClass) {
HttpEntity responseEntity = response.getEntity();
ObjectMapper objectMapper = (ObjectMapper) Options.getOption(Option.OBJECT_MAPPER);
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
String headerName = header.getName();
List<String> list = headers.get(headerName);
if (list == null)
list = new ArrayList<String>();
list.add(header.getValue());
headers.put(headerName, list);
StatusLine statusLine = response.getStatusLine();
this.statusCode = statusLine.getStatusCode();
this.statusText = statusLine.getReasonPhrase();
Header contentType = responseEntity.getContentType();
if (contentType != null) {
String responseCharset = ResponseUtils.getCharsetFromContentType(contentType.getValue());
if (responseCharset != null && !responseCharset.trim().equals("")) {
charset = responseCharset;
EntityUtils.consumeQuietly(responseEntity);
代码示例来源:origin: xtuhcy/gecco
reqObj = new HttpGet(request.getUrl());
int status = response.getStatusLine().getStatusCode();
HttpResponse resp = new HttpResponse();
resp.setStatus(status);
if(status == 302 || status == 301) {
String redirectUrl = response.getFirstHeader("Location").getValue();
resp.setContent(UrlUtils.relative2Absolute(request.getUrl(), redirectUrl));
} else if(status == 200) {
HttpEntity responseEntity = response.getEntity();
ByteArrayInputStream raw = toByteInputStream(responseEntity.getContent());
resp.setRaw(raw);
String contentType = null;
Header contentTypeHeader = responseEntity.getContentType();
if(contentTypeHeader != null) {
contentType = contentTypeHeader.getValue();
resp.setCharset(charset);
String content = getContent(raw, responseEntity.getContentLength(), charset);
resp.setContent(content);
代码示例来源:origin: alibaba/Sentinel
private void handleResponse(final HttpResponse response, MachineInfo machine,
Map<String, MetricEntity> metricMap) throws Exception {
int code = response.getStatusLine().getStatusCode();
if (code != HTTP_OK) {
return;
}
Charset charset = null;
try {
String contentTypeStr = response.getFirstHeader("Content-type").getValue();
if (StringUtil.isNotEmpty(contentTypeStr)) {
ContentType contentType = ContentType.parse(contentTypeStr);
charset = contentType.getCharset();
}
} catch (Exception ignore) {
}
String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) {
//logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + ", bodyStr is empty");
return;
}
String[] lines = body.split("\n");
//logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() +
// ", bodyStr.length()=" + body.length() + ", lines=" + lines.length);
handleBody(lines, machine, metricMap);
}
代码示例来源:origin: sarxos/webcam-capture
private InputStream get(final URI uri, boolean withoutImageMime) throws UnsupportedOperationException, IOException {
final HttpGet get = new HttpGet(uri);
final HttpResponse respone = client.execute(get, context);
final HttpEntity entity = respone.getEntity();
// normal jpeg return image/jpeg as opposite to mjpeg
if (withoutImageMime) {
final Header contentType = entity.getContentType();
if (contentType == null) {
throw new WebcamException("Content Type header is missing");
}
if (contentType.getValue().startsWith("image/")) {
throw new WebcamException("Cannot read images in PUSH mode, change mode to PULL " + contentType);
}
}
return entity.getContent();
}
代码示例来源:origin: medcl/elasticsearch-analysis-ik
CloseableHttpResponse response;
BufferedReader in;
HttpGet get = new HttpGet(location);
get.setConfig(rc);
try {
response = httpclient.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
if (response.getEntity().getContentType().getValue().contains("charset=")) {
String contentType = response.getEntity().getContentType().getValue();
charset = contentType.substring(contentType.lastIndexOf("=") + 1);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
String line;
while ((line = in.readLine()) != null) {
代码示例来源:origin: searchbox-io/Jest
private <T extends JestResult> T deserializeResponse(HttpResponse response, final HttpRequest httpRequest, Action<T> clientRequest) throws IOException {
StatusLine statusLine = response.getStatusLine();
try {
return clientRequest.createNewElasticSearchResult(
response.getEntity() == null ? null : EntityUtils.toString(response.getEntity()),
statusLine.getStatusCode(),
statusLine.getReasonPhrase(),
gson
);
} catch (com.google.gson.JsonSyntaxException e) {
for (Header header : response.getHeaders("Content-Type")) {
final String mimeType = header.getValue();
if (!mimeType.startsWith("application/json")) {
// probably a proxy that responded in text/html
final String message = "Request " + httpRequest.toString() + " yielded " + mimeType
+ ", should be json: " + statusLine.toString();
throw new IOException(message, e);
}
}
throw e;
}
}
代码示例来源:origin: apache/nifi
final int responseCode = response.getStatusLine().getStatusCode();
logger.debug("initiateTransaction responseCode={}", responseCode);
switch (responseCode) {
case RESPONSE_CODE_CREATED:
EntityUtils.consume(response.getEntity());
throw new ProtocolException("Server returned RESPONSE_CODE_CREATED without Location header");
final Header transportProtocolVersionHeader = response.getFirstHeader(HttpHeaders.PROTOCOL_VERSION);
if (transportProtocolVersionHeader == null) {
throw new ProtocolException("Server didn't return confirmed protocol version");
final Integer protocolVersionConfirmedByServer = Integer.valueOf(transportProtocolVersionHeader.getValue());
logger.debug("Finished version negotiation, protocolVersionConfirmedByServer={}", protocolVersionConfirmedByServer);
transportProtocolVersionNegotiator.setVersion(protocolVersionConfirmedByServer);
throw new ProtocolException("Server didn't return " + HttpHeaders.SERVER_SIDE_TRANSACTION_TTL);
serverTransactionTtl = Integer.parseInt(serverTransactionTtlHeader.getValue());
break;
try (InputStream content = response.getEntity().getContent()) {
throw handleErrResponse(responseCode, content);
代码示例来源:origin: jamesdbloom/mockserver
request.addHeader(cookieTwoHeader);
request.setEntity(new StringEntity("an_example_body"));
HttpResponse response = httpClient.execute(request);
assertEquals(HttpStatusCode.OK_200.code(), response.getStatusLine().getStatusCode());
assertThat(response.getHeaders("Set-Cookie").length, is(2));
assertThat(response.getHeaders("Set-Cookie")[0].getValue(), is(setCookieOneHeader.getValue()));
assertThat(response.getHeaders("Set-Cookie")[1].getValue(), is(setCookieTwoHeader.getValue()));
assertEquals("an_example_body", new String(EntityUtils.toByteArray(response.getEntity()), UTF_8));
.withMethod("POST")
.withPath("/test_headers_and_body")
.withHeader(setCookieOneHeader.getName(), setCookieOneHeader.getValue())
.withHeader(setCookieTwoHeader.getName(), setCookieTwoHeader.getValue())
.withCookie("personalization_59996b985e24ce008d3df3bd07e27c1b", "")
.withCookie("anonymous_59996b985e24ce008d3df3bd07e27c1b", "acgzEaAKOVR=mAY9yJhP7IrC9Am")
内容来源于网络,如有侵权,请联系作者删除!