Search in sources :

Example 1 with Blob

use of com.gargoylesoftware.htmlunit.javascript.host.file.Blob in project htmlunit by HtmlUnit.

the class XMLHttpRequest method getResponse.

/**
 * @return returns the response's body content as an ArrayBuffer, Blob, Document, JavaScript Object,
 * or DOMString, depending on the value of the request's responseType property.
 */
@JsxGetter
public Object getResponse() {
    if (RESPONSE_TYPE_DEFAULT.equals(responseType_) || RESPONSE_TYPE_TEXT.equals(responseType_)) {
        return getResponseText();
    }
    if (state_ != DONE) {
        return null;
    }
    if (webResponse_ instanceof NetworkErrorWebResponse) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("XMLHttpRequest.responseXML returns of a network error (" + ((NetworkErrorWebResponse) webResponse_).getError() + ")");
        }
        return null;
    }
    if (RESPONSE_TYPE_ARRAYBUFFER.equals(responseType_)) {
        final NativeArrayBuffer nativeArrayBuffer = new NativeArrayBuffer(webResponse_.getContentLength());
        try {
            final int bufferLength = 1;
            final byte[] buffer = new byte[bufferLength];
            try (InputStream inputStream = webResponse_.getContentAsStream()) {
                int offset = 0;
                int readLen;
                while ((readLen = inputStream.read(buffer, 0, bufferLength)) != -1) {
                    System.arraycopy(buffer, 0, nativeArrayBuffer.getBuffer(), offset, readLen);
                    offset += readLen;
                }
            }
            nativeArrayBuffer.setParentScope(getParentScope());
            nativeArrayBuffer.setPrototype(ScriptableObject.getClassPrototype(getWindow(), nativeArrayBuffer.getClassName()));
            return nativeArrayBuffer;
        } catch (final IOException e) {
            webResponse_ = new NetworkErrorWebResponse(webRequest_, e);
            return null;
        }
    } else if (RESPONSE_TYPE_BLOB.equals(responseType_)) {
        try {
            if (webResponse_ != null) {
                try (InputStream inputStream = webResponse_.getContentAsStream()) {
                    final Blob blob = new Blob(IOUtils.toByteArray(inputStream), webResponse_.getContentType());
                    blob.setParentScope(getParentScope());
                    blob.setPrototype(ScriptableObject.getClassPrototype(getWindow(), blob.getClassName()));
                    return blob;
                }
            }
        } catch (final IOException e) {
            webResponse_ = new NetworkErrorWebResponse(webRequest_, e);
            return null;
        }
    } else if (RESPONSE_TYPE_DOCUMENT.equals(responseType_)) {
        if (webResponse_ != null) {
            try {
                final Charset encoding = webResponse_.getContentCharset();
                if (encoding == null) {
                    return "";
                }
                final String content = webResponse_.getContentAsString(encoding);
                if (content == null) {
                    return "";
                }
                return DOMParser.parseFromString(this, content, webResponse_.getContentType());
            } catch (final IOException e) {
                webResponse_ = new NetworkErrorWebResponse(webRequest_, e);
                return null;
            }
        }
    } else if (RESPONSE_TYPE_JSON.equals(responseType_)) {
        if (webResponse_ != null) {
            final Charset encoding = webResponse_.getContentCharset();
            if (encoding == null) {
                return null;
            }
            final String content = webResponse_.getContentAsString(encoding);
            if (content == null) {
                return null;
            }
            try {
                return new JsonParser(Context.getCurrentContext(), this).parseValue(content);
            } catch (final ParseException e) {
                webResponse_ = new NetworkErrorWebResponse(webRequest_, new IOException(e));
                return null;
            }
        }
    }
    return "";
}
Also used : Blob(com.gargoylesoftware.htmlunit.javascript.host.file.Blob) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) NativeArrayBuffer(net.sourceforge.htmlunit.corejs.javascript.typedarrays.NativeArrayBuffer) IOException(java.io.IOException) ParseException(net.sourceforge.htmlunit.corejs.javascript.json.JsonParser.ParseException) HttpHint(com.gargoylesoftware.htmlunit.WebRequest.HttpHint) JsonParser(net.sourceforge.htmlunit.corejs.javascript.json.JsonParser) JsxGetter(com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter)

Example 2 with Blob

use of com.gargoylesoftware.htmlunit.javascript.host.file.Blob 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);
                }
            }
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Blob(com.gargoylesoftware.htmlunit.javascript.host.file.Blob) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) URLSearchParams(com.gargoylesoftware.htmlunit.javascript.host.URLSearchParams) NoHttpResponseException(org.apache.http.NoHttpResponseException) SocketTimeoutException(java.net.SocketTimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParseException(net.sourceforge.htmlunit.corejs.javascript.json.JsonParser.ParseException) StringWriter(java.io.StringWriter) NativeArrayBufferView(net.sourceforge.htmlunit.corejs.javascript.typedarrays.NativeArrayBufferView)

Aggregations

Blob (com.gargoylesoftware.htmlunit.javascript.host.file.Blob)2 IOException (java.io.IOException)2 ParseException (net.sourceforge.htmlunit.corejs.javascript.json.JsonParser.ParseException)2 HttpHint (com.gargoylesoftware.htmlunit.WebRequest.HttpHint)1 JsxGetter (com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter)1 URLSearchParams (com.gargoylesoftware.htmlunit.javascript.host.URLSearchParams)1 HTMLDocument (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument)1 InputStream (java.io.InputStream)1 StringWriter (java.io.StringWriter)1 MalformedURLException (java.net.MalformedURLException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 Charset (java.nio.charset.Charset)1 Transformer (javax.xml.transform.Transformer)1 DOMSource (javax.xml.transform.dom.DOMSource)1 StreamResult (javax.xml.transform.stream.StreamResult)1 JsonParser (net.sourceforge.htmlunit.corejs.javascript.json.JsonParser)1 NativeArrayBuffer (net.sourceforge.htmlunit.corejs.javascript.typedarrays.NativeArrayBuffer)1 NativeArrayBufferView (net.sourceforge.htmlunit.corejs.javascript.typedarrays.NativeArrayBufferView)1 NoHttpResponseException (org.apache.http.NoHttpResponseException)1