use of net.sourceforge.htmlunit.corejs.javascript.typedarrays.NativeArrayBufferView in project htmlunit by HtmlUnit.
the class XMLHttpRequest method prepareRequestContent.
/**
* Prepares the WebRequest that will be sent.
* @param content the content to send
*/
private void prepareRequestContent(final Object content) {
if (content != null && (HttpMethod.POST == webRequest_.getHttpMethod() || HttpMethod.PUT == webRequest_.getHttpMethod() || HttpMethod.PATCH == webRequest_.getHttpMethod()) && !Undefined.isUndefined(content)) {
final boolean setEncodingType = webRequest_.getAdditionalHeader(HttpHeader.CONTENT_TYPE) == null;
if (content instanceof HTMLDocument) {
// final String body = ((HTMLDocument) content).getDomNodeOrDie().asXml();
final String body = new XMLSerializer().serializeToString((HTMLDocument) content);
if (LOG.isDebugEnabled()) {
LOG.debug("Setting request body to: " + body);
}
webRequest_.setRequestBody(body);
if (setEncodingType) {
webRequest_.setAdditionalHeader(HttpHeader.CONTENT_TYPE, "text/html;charset=UTF-8");
}
} else if (content instanceof XMLDocument) {
// this output differs from real browsers but it seems to be a good starting point
try (StringWriter writer = new StringWriter()) {
final XMLDocument xmlDocument = (XMLDocument) content;
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.transform(new DOMSource(xmlDocument.getDomNodeOrDie().getFirstChild()), new StreamResult(writer));
final String body = writer.toString();
if (LOG.isDebugEnabled()) {
LOG.debug("Setting request body to: " + body);
}
webRequest_.setRequestBody(body);
if (setEncodingType) {
webRequest_.setAdditionalHeader(HttpHeader.CONTENT_TYPE, MimeType.APPLICATION_XML + ";charset=UTF-8");
}
} catch (final Exception e) {
Context.throwAsScriptRuntimeEx(e);
}
} else if (content instanceof FormData) {
((FormData) content).fillRequest(webRequest_);
} else if (content instanceof NativeArrayBufferView) {
final NativeArrayBufferView view = (NativeArrayBufferView) content;
webRequest_.setRequestBody(new String(view.getBuffer().getBuffer(), UTF_8));
if (setEncodingType) {
webRequest_.setEncodingType(null);
}
} else if (content instanceof URLSearchParams) {
((URLSearchParams) content).fillRequest(webRequest_);
webRequest_.addHint(HttpHint.IncludeCharsetInContentTypeHeader);
} else if (content instanceof Blob) {
((Blob) content).fillRequest(webRequest_);
} else {
final String body = Context.toString(content);
if (!body.isEmpty()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Setting request body to: " + body);
}
webRequest_.setRequestBody(body);
webRequest_.setCharset(UTF_8);
if (setEncodingType) {
webRequest_.setEncodingType(FormEncodingType.TEXT_PLAIN);
}
}
}
}
}
Aggregations