/** * Writes out the content of the given HTTP entity to the session output * buffer based on properties of the given HTTP message. * * @param outbuffer the output session buffer. * @param message the HTTP message. * @param entity the HTTP entity to be written out. * @throws HttpException in case of HTTP protocol violation. * @throws IOException in case of an I/O error. */ public void serialize( final SessionOutputBuffer outbuffer, final HttpMessage message, final HttpEntity entity) throws HttpException, IOException { if (outbuffer == null) { throw new IllegalArgumentException("Session output buffer may not be null"); } if (message == null) { throw new IllegalArgumentException("HTTP message may not be null"); } if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } OutputStream outstream = doSerialize(outbuffer, message); entity.writeTo(outstream); outstream.close(); }
public static void moveMIMEHeadersToHTTPHeader (@Nonnull final MimeMessage aMimeMsg, @Nonnull final HttpMessage aHttpMsg) throws MessagingException { ValueEnforcer.notNull (aMimeMsg, "MimeMsg"); ValueEnforcer.notNull (aHttpMsg, "HttpMsg"); // Move all mime headers to the HTTP request final Enumeration <Header> aEnum = aMimeMsg.getAllHeaders (); while (aEnum.hasMoreElements ()) { final Header h = aEnum.nextElement (); // Make a single-line HTTP header value! aHttpMsg.addHeader (h.getName (), HttpHeaderMap.getUnifiedValue (h.getValue ())); // Remove from MIME message! aMimeMsg.removeHeader (h.getName ()); } }
/** helper function to fill the request with header entries . * */ private static HttpMessage completeRequest(HttpMessage request, List<NameValuePair> headerEntries){ if (null == request){ logger.error("unable to complete request as the passed request object is null"); return request; } // dump all the header entries to the request. if (null != headerEntries && headerEntries.size() > 0){ for (NameValuePair pair : headerEntries){ request.addHeader(pair.getName(), pair.getValue()); } } return request; }
protected void setHeaders(final HttpMessage base, final String headers) throws IOException { try (BufferedReader reader = new BufferedReader(new StringReader(headers))) { String line = reader.readLine(); while (line != null) { int colonIndex = line.indexOf(":"); if (colonIndex > 0) { String headerName = line.substring(0, colonIndex); if (line.length() > colonIndex + 2) { base.addHeader(headerName, line.substring(colonIndex + 1)); } else { base.addHeader(headerName, null); } line = reader.readLine(); } else { throw new FlowableException(HTTP_TASK_REQUEST_HEADERS_INVALID); } } } }
private String generateViaHeader(final HttpMessage msg) { final ProtocolVersion pv = msg.getProtocolVersion(); final String existingEntry = viaHeaders.get(pv); if (existingEntry != null) { return existingEntry; } final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader()); final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; String value; if ("http".equalsIgnoreCase(pv.getProtocol())) { value = String.format("%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getMajor(), pv.getMinor(), release); } else { value = String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getProtocol(), pv.getMajor(), pv.getMinor(), release); } viaHeaders.put(pv, value); return value; }
private String generateViaHeader(final HttpMessage msg) { final ProtocolVersion pv = msg.getProtocolVersion(); final String existingEntry = viaHeaders.get(pv); if (existingEntry != null) { return existingEntry; } final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader()); final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; String value; final int major = pv.getMajor(); final int minor = pv.getMinor(); if ("http".equalsIgnoreCase(pv.getProtocol())) { value = String.format("%d.%d localhost (Apache-HttpClient/%s (cache))", major, minor, release); } else { value = String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getProtocol(), major, minor, release); } viaHeaders.put(pv, value); return value; }
/** * Helper method to set the HTTP headers required for all HTTP requests. * * @param httpMessage HTTP message */ private void addCMCHeaders(HttpMessage httpMessage) { // Set the Accepts and Content Type headers httpMessage.addHeader(HttpHeaders.ACCEPT, "application/json"); httpMessage.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); // Custom header for CSRF protection httpMessage.addHeader("X-Requested-By", "12345"); // Add a user agent header httpMessage.addHeader("User-Agent", "cmc-java " + CMC_VERSION); // Set the basic authorization headers. String auth = accountID + ":" + authenticationToken; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII)); String authHeader = "Basic " + new String(encodedAuth, StandardCharsets.US_ASCII); httpMessage.addHeader(HttpHeaders.AUTHORIZATION, authHeader); }
protected void recordCookie(HttpMessage httpMessage, Trace trace) { org.apache.http.Header[] cookies = httpMessage.getHeaders("Cookie"); for (org.apache.http.Header header : cookies) { final String value = header.getValue(); if (StringUtils.hasLength(value)) { if (cookieSampler.isSampling()) { final SpanEventRecorder recorder = trace.currentSpanEventRecorder(); recorder.recordAttribute(AnnotationKey.HTTP_COOKIE, StringUtils.abbreviate(value, 1024)); } // Can a cookie have 2 or more values? // PMD complains if we use break here return; } } }
protected void recordEntity(HttpMessage httpMessage, Trace trace) { if (httpMessage instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpMessage; try { final HttpEntity entity = entityRequest.getEntity(); if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) { if (entitySampler.isSampling()) { final String entityString = entityUtilsToString(entity, Charsets.UTF_8_NAME, 1024); final SpanEventRecorder recorder = trace.currentSpanEventRecorder(); recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityString); } } } catch (Exception e) { logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e); } } }
protected void recordEntity(HttpMessage httpMessage, SpanEventRecorder recorder) { if (httpMessage instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpMessage; try { final HttpEntity entity = entityRequest.getEntity(); if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) { if (entitySampler.isSampling()) { final String entityString = entityUtilsToString(entity, Charsets.UTF_8_NAME, 1024); recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityString); } } } catch (Exception e) { logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e); } } }
@Test public final void getCoapOptionsContentTypeTest() { // create the message HttpMessage httpMessage = new BasicHttpRequest("get", "http://localhost"); // create the header String headerName = "content-type"; String headerValue = "text/plain"; Header header = new BasicHeader(headerName, headerValue); httpMessage.addHeader(header); // translate the header List<Option> options = HttpTranslator.getCoapOptions(httpMessage.getAllHeaders()); // the context-type should not be handled by this method assertTrue(options.isEmpty()); }
@Test public final void getCoapOptionsMaxAgeTest() { // create the message HttpMessage httpMessage = new BasicHttpRequest("get", "http://localhost"); // create the header String headerName = "cache-control"; int maxAge = 25; String headerValue = "max-age=" + maxAge; Header header = new BasicHeader(headerName, headerValue); httpMessage.addHeader(header); // translate the header List<Option> options = HttpTranslator.getCoapOptions(httpMessage.getAllHeaders()); assertFalse(options.isEmpty()); assertTrue(options.size() == 1); // get the option list Message coapMessage = new GETRequest(); coapMessage.setOptions(options); Option testedOption = coapMessage.getFirstOption(OptionNumberRegistry.MAX_AGE); assertNotNull(testedOption); assertEquals(maxAge, testedOption.getIntValue()); }
@Test public final void getCoapOptionsMaxAgeTest2() { // create the message HttpMessage httpMessage = new BasicHttpRequest("get", "http://localhost"); // create the header String headerName = "cache-control"; String headerValue = "no-cache"; Header header = new BasicHeader(headerName, headerValue); httpMessage.addHeader(header); // translate the header List<Option> options = HttpTranslator.getCoapOptions(httpMessage.getAllHeaders()); assertFalse(options.isEmpty()); assertTrue(options.size() == 1); // get the option list Message coapMessage = new GETRequest(); coapMessage.setOptions(options); Option testedOption = coapMessage.getFirstOption(OptionNumberRegistry.MAX_AGE); assertNotNull(testedOption); assertEquals(0, testedOption.getIntValue()); }
/** * Test method for * {@link ch.ethz.inf.vs.californium.util.HttpTranslator#getCoapOptions(org.apache.http.HttpMessage)} * . */ @Test public final void getCoapOptionsTest() { // create the message HttpMessage httpMessage = new BasicHttpRequest("get", "http://localhost"); // create the header String headerName = "if-match"; String headerValue = "\"737060cd8c284d8af7ad3082f209582d\""; Header header = new BasicHeader(headerName, headerValue); httpMessage.addHeader(header); // translate the header List<Option> options = HttpTranslator.getCoapOptions(httpMessage.getAllHeaders()); assertFalse(options.isEmpty()); // get the option list Message coapMessage = new GETRequest(); coapMessage.setOptions(options); int optionNumber = Integer.parseInt(HttpTranslator.HTTP_TRANSLATION_PROPERTIES.getProperty("http.message.header." + headerName)); assertEquals(coapMessage.getFirstOption(optionNumber).getStringValue(), headerValue); }
/** * Sets the headers of an HTTP request necessary to execute. * * @param httpMessage The HTTP request to add the basic headers. * @param headers A map of key-value pairs representing the headers. */ public static void setHeaders( HttpMessage httpMessage, Map<String,String> headers ) { if( headers == null ) { httpMessage.setHeader( "Accept-Language", "en-us,en;q=0.5" ); return; } else if( !headers.containsKey( "Accept-Language" ) ) { headers.put( "Accept-Language", "en-us,en;q=0.5" ); } for( Map.Entry<String, String> entry : headers.entrySet() ) { httpMessage.setHeader( entry.getKey(), entry.getValue() ); } }
private String generateViaHeader(HttpMessage msg) { final VersionInfo vi = VersionInfo.loadVersionInfo( "org.apache.http.client", getClass().getClassLoader()); final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; final ProtocolVersion pv = msg.getProtocolVersion(); if ("http".equalsIgnoreCase(pv.getProtocol())) { return String.format( "%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getMajor(), pv.getMinor(), release); } else { return String.format( "%s/%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getProtocol(), pv.getMajor(), pv.getMinor(), release); } }
/** * Creates a {@link BasicHttpEntity} based on properties of the given * message. The content of the entity is created by wrapping * {@link SessionInputBuffer} with a content decoder depending on the * transfer mechanism used by the message. * <p> * This method is called by the public * {@link #deserialize(SessionInputBuffer, HttpMessage)}. * * @param inbuffer the session input buffer. * @param message the message. * @return HTTP entity. * @throws HttpException in case of HTTP protocol violation. * @throws IOException in case of an I/O error. */ protected BasicHttpEntity doDeserialize( final SessionInputBuffer inbuffer, final HttpMessage message) throws HttpException, IOException { BasicHttpEntity entity = new BasicHttpEntity(); long len = this.lenStrategy.determineLength(message); if (len == ContentLengthStrategy.CHUNKED) { entity.setChunked(true); entity.setContentLength(-1); entity.setContent(new ChunkedInputStream(inbuffer)); } else if (len == ContentLengthStrategy.IDENTITY) { entity.setChunked(false); entity.setContentLength(-1); entity.setContent(new IdentityInputStream(inbuffer)); } else { entity.setChunked(false); entity.setContentLength(len); entity.setContent(new ContentLengthInputStream(inbuffer, len)); } Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); if (contentTypeHeader != null) { entity.setContentType(contentTypeHeader); } Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); if (contentEncodingHeader != null) { entity.setContentEncoding(contentEncodingHeader); } return entity; }
public long determineLength(final HttpMessage message) throws HttpException { long result = this.contentLengthStrategy.determineLength(message); if (result == ContentLengthStrategy.IDENTITY) { throw new ProtocolException("Identity transfer encoding cannot be used"); } return result; }
@Override protected HttpMessage parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new NoHttpResponseException("The target server failed to respond"); } //create the status line from the status string ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); return this.responseFactory.newHttpResponse(statusline, null); }
@Override protected HttpMessage parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new ConnectionClosedException("Client closed connection"); } ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); return this.requestFactory.newHttpRequest(requestline); }
/** * @param message * @param headers */ private void setHeaders(HttpMessage message, Map<String, String> headers) { if (headers == null) return; for (Entry<String, String> entry : headers.entrySet()) { message.setHeader(entry.getKey(), entry.getValue().toString()); } }
/** * 设置Http头部,同时添加上公共的类型,长连接,COS SDK标识 * * @param message HTTP消息 * @param headers 用户额外添加的HTTP头部 */ private void setHeaders(HttpMessage message, Map<String, String> headers) { message.setHeader(RequestHeaderKey.ACCEPT, RequestHeaderValue.Accept.ALL); message.setHeader(RequestHeaderKey.CONNECTION, RequestHeaderValue.Connection.KEEP_ALIVE); message.setHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent()); if (headers != null) { for (String headerKey : headers.keySet()) { message.setHeader(headerKey, headers.get(headerKey)); } } }
public long determineLength(final HttpMessage message) throws HttpException { final long result = this.contentLengthStrategy.determineLength(message); if (result == ContentLengthStrategy.IDENTITY) { throw new ProtocolException("Identity transfer encoding cannot be used"); } return result; }
protected HttpEntity prepareInput(final HttpMessage message) throws HttpException { final BasicHttpEntityHC4 entity = new BasicHttpEntityHC4(); final long len = this.incomingContentStrategy.determineLength(message); final InputStream instream = createInputStream(len, this.inbuffer); if (len == ContentLengthStrategy.CHUNKED) { entity.setChunked(true); entity.setContentLength(-1); entity.setContent(instream); } else if (len == ContentLengthStrategy.IDENTITY) { entity.setChunked(false); entity.setContentLength(-1); entity.setContent(instream); } else { entity.setChunked(false); entity.setContentLength(len); entity.setContent(instream); } final Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); if (contentTypeHeader != null) { entity.setContentType(contentTypeHeader); } final Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); if (contentEncodingHeader != null) { entity.setContentEncoding(contentEncodingHeader); } return entity; }
public void write(final HttpMessage message) throws IOException, HttpException { Args.notNull(message, "HTTP message"); writeHeadLine(message); for (final HeaderIterator it = message.headerIterator(); it.hasNext(); ) { final Header header = it.nextHeader(); this.sessionBuffer.writeLine (lineFormatter.formatHeader(this.lineBuf, header)); } this.lineBuf.clear(); this.sessionBuffer.writeLine(this.lineBuf); }
private static void setHeaders(HttpMessage httpMessage, Map<String, String> headers) { if (headers != null) { Iterator<Map.Entry<String, String>> entries = headers.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); httpMessage.setHeader(entry.getKey(), entry.getValue()); } } }
protected String get(final String headerName, final HttpMessage message) { Header header = message.getFirstHeader(headerName); if (header!=null) return header.getValue(); else return ""; }
protected boolean has(final String headerName, final String headerValueOrElement, final HttpMessage message) { Header[] headers = message.getHeaders(headerName); for (Header header : headers) { if (header.getValue().equals(headerValueOrElement)) return true; HeaderElement[] elements = header.getElements(); for (HeaderElement element : elements) if (element.getName().equals(headerValueOrElement)) return true; } return false; }
protected String get(final String headerName, final String elementName, final HttpMessage message) { Header header = message.getFirstHeader(headerName); if (header==null) return ""; HeaderElement[] elements = header.getElements(); for (HeaderElement element : elements) if (element.getName().equals(elementName)) return element.getValue(); return ""; }
private void processSsdpPacket(DatagramPacket packet) { byte[] data = new byte[packet.getLength()]; System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength()); HttpMessage message = getHttpMessage(data); if (message == null) return; Header mandatoryExtensionHeader = message.getFirstHeader("man"); if (mandatoryExtensionHeader == null || !mandatoryExtensionHeader.getValue().equals("\"ssdp:discover\"")) return; Header serviceTypeHeader = message.getFirstHeader("st"); if (serviceTypeHeader == null) return; if (serviceTypeHeader.getValue().equals("ssdp:all") || serviceTypeHeader.getValue().equals(serviceType)) { // respond String ip = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress()); String response = String.format(responseTemplate, getServiceId(), ip, getPort()); DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.length(), packet.getAddress(), packet.getPort()); try { DatagramSocket sendingSocket = new DatagramSocket(); sendingSocket.send(responsePacket); sendingSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
protected boolean hasCacheControlParameterFrom(final HttpMessage msg, final String[] params) { final Header[] cacheControlHeaders = msg.getHeaders(HeaderConstants.CACHE_CONTROL); for (final Header header : cacheControlHeaders) { for (final HeaderElement elem : header.getElements()) { for (final String param : params) { if (param.equalsIgnoreCase(elem.getName())) { return true; } } } } return false; }
public static boolean isEndToEndHeaderSubset(final HttpMessage r1, final HttpMessage r2) { for (final Header h : r1.getAllHeaders()) { if (!isHopByHopHeader(h.getName())) { final String r1val = getCanonicalHeaderValue(r1, h.getName()); final String r2val = getCanonicalHeaderValue(r2, h.getName()); if (!r1val.equals(r2val)) { return false; } } } return true; }
public HttpMessage parse() throws HttpException, IOException { // if (!isReadyForParsing()) { // throw new IllegalArgumentException( // "not ready for parsing, some packets are out-of-order"); // } if (log.isDebugEnabled()) { log.debug("parsing stream: " + key); } // byte[] data = getDataAsBuffer().buffer(); byte[] data = getDataAsBuffer().toByteArray(); SessionInputBuffer input = new SessionInputBufferMockup(data); HttpMessage msg = null; switch (type) { case TYPE_REQUEST: HttpRequestParser requestParser = new HttpRequestParser(input, lineParser, requestFactory, new BasicHttpParams()); msg = requestParser.parse(); break; case TYPE_RESPONSE: HttpResponseParser responseParser = new HttpResponseParser(input, lineParser, responseFactory, new BasicHttpParams()); msg = responseParser.parse(); ((HttpResponse) msg).setEntity(entityDeserializer.deserialize(input, msg)); break; } return msg; }
private static Multimap<String, String> buildCanonicalizedHeadersMap(HttpMessage request) { Header[] headers = request.getAllHeaders(); SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create(); for (Header header : headers) { if (header.getName() == null) { continue; } String key = header.getName().toLowerCase(); canonicalizedHeaders.put(key, header.getValue()); } return canonicalizedHeaders; }
/** * 设置Http头部,同时添加上公共的类型,长连接,COS SDK标识 * * @param message * HTTP消息 * @param headers * 用户额外添加的HTTP头部 */ private void setHeaders(HttpMessage message, Map<String, String> headers) { message.setHeader(RequestHeaderKey.ACCEPT, RequestHeaderValue.Accept.ALL); message.setHeader(RequestHeaderKey.CONNECTION, RequestHeaderValue.Connection.KEEP_ALIVE); message.setHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent()); if (headers != null) { for (String headerKey : headers.keySet()) { message.setHeader(headerKey, headers.get(headerKey)); } } }
public static void add(HttpMessage httpMessage, Headers headers) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { for (String value : entry.getValue()) { httpMessage.addHeader(entry.getKey(), value); } } }
public static Headers get(HttpMessage httpMessage) { Headers headers = new Headers(); for (Header header : httpMessage.getAllHeaders()) { headers.add(header.getName(), header.getValue()); } return headers; }