Search in sources :

Example 1 with ContentType

use of org.nanohttpd.protocols.http.content.ContentType in project nanohttpd by NanoHttpd.

the class Response method send.

/**
     * Sends given response to the socket.
     */
public void send(OutputStream outputStream) {
    SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    try {
        if (this.status == null) {
            throw new Error("sendResponse(): Status can't be null.");
        }
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false);
        pw.append("HTTP/1.1 ").append(this.status.getDescription()).append(" \r\n");
        if (this.mimeType != null) {
            printHeader(pw, "Content-Type", this.mimeType);
        }
        if (getHeader("date") == null) {
            printHeader(pw, "Date", gmtFrmt.format(new Date()));
        }
        for (Entry<String, String> entry : this.header.entrySet()) {
            printHeader(pw, entry.getKey(), entry.getValue());
        }
        for (String cookieHeader : this.cookieHeaders) {
            printHeader(pw, "Set-Cookie", cookieHeader);
        }
        if (getHeader("connection") == null) {
            printHeader(pw, "Connection", (this.keepAlive ? "keep-alive" : "close"));
        }
        if (getHeader("content-length") != null) {
            setUseGzip(false);
        }
        if (useGzipWhenAccepted()) {
            printHeader(pw, "Content-Encoding", "gzip");
            setChunkedTransfer(true);
        }
        long pending = this.data != null ? this.contentLength : 0;
        if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
            printHeader(pw, "Transfer-Encoding", "chunked");
        } else if (!useGzipWhenAccepted()) {
            pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);
        }
        pw.append("\r\n");
        pw.flush();
        sendBodyWithCorrectTransferAndEncoding(outputStream, pending);
        outputStream.flush();
        NanoHTTPD.safeClose(this.data);
    } catch (IOException ioe) {
        NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe);
    }
}
Also used : ContentType(org.nanohttpd.protocols.http.content.ContentType) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter)

Example 2 with ContentType

use of org.nanohttpd.protocols.http.content.ContentType in project nanohttpd by NanoHttpd.

the class HTTPSession method parseBody.

@Override
public void parseBody(Map<String, String> files) throws IOException, ResponseException {
    RandomAccessFile randomAccessFile = null;
    try {
        long size = getBodySize();
        ByteArrayOutputStream baos = null;
        DataOutput requestDataOutput = null;
        // Store the request in memory or a file, depending on size
        if (size < MEMORY_STORE_LIMIT) {
            baos = new ByteArrayOutputStream();
            requestDataOutput = new DataOutputStream(baos);
        } else {
            randomAccessFile = getTmpBucket();
            requestDataOutput = randomAccessFile;
        }
        // Read all the body and write it to request_data_output
        byte[] buf = new byte[REQUEST_BUFFER_LEN];
        while (this.rlen >= 0 && size > 0) {
            this.rlen = this.inputStream.read(buf, 0, (int) Math.min(size, REQUEST_BUFFER_LEN));
            size -= this.rlen;
            if (this.rlen > 0) {
                requestDataOutput.write(buf, 0, this.rlen);
            }
        }
        ByteBuffer fbuf = null;
        if (baos != null) {
            fbuf = ByteBuffer.wrap(baos.toByteArray(), 0, baos.size());
        } else {
            fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
            randomAccessFile.seek(0);
        }
        // in data section, too, read it:
        if (Method.POST.equals(this.method)) {
            ContentType contentType = new ContentType(this.headers.get("content-type"));
            if (contentType.isMultipart()) {
                String boundary = contentType.getBoundary();
                if (boundary == null) {
                    throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
                }
                decodeMultipartFormData(contentType, fbuf, this.parms, files);
            } else {
                byte[] postBytes = new byte[fbuf.remaining()];
                fbuf.get(postBytes);
                String postLine = new String(postBytes, contentType.getEncoding()).trim();
                // Handle application/x-www-form-urlencoded
                if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType.getContentType())) {
                    decodeParms(postLine, this.parms);
                } else if (postLine.length() != 0) {
                    // Special case for raw POST data => create a
                    // special files entry "postData" with raw content
                    // data
                    files.put(POST_DATA, postLine);
                }
            }
        } else if (Method.PUT.equals(this.method)) {
            files.put("content", saveTmpFile(fbuf, 0, fbuf.limit(), null));
        }
    } finally {
        NanoHTTPD.safeClose(randomAccessFile);
    }
}
Also used : DataOutput(java.io.DataOutput) RandomAccessFile(java.io.RandomAccessFile) ContentType(org.nanohttpd.protocols.http.content.ContentType) ResponseException(org.nanohttpd.protocols.http.NanoHTTPD.ResponseException) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer)

Example 3 with ContentType

use of org.nanohttpd.protocols.http.content.ContentType in project nanohttpd by NanoHttpd.

the class Response method newFixedLengthResponse.

/**
     * Create a text response with known length.
     */
public static Response newFixedLengthResponse(IStatus status, String mimeType, String txt) {
    ContentType contentType = new ContentType(mimeType);
    if (txt == null) {
        return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);
    } else {
        byte[] bytes;
        try {
            CharsetEncoder newEncoder = Charset.forName(contentType.getEncoding()).newEncoder();
            if (!newEncoder.canEncode(txt)) {
                contentType = contentType.tryUTF8();
            }
            bytes = txt.getBytes(contentType.getEncoding());
        } catch (UnsupportedEncodingException e) {
            NanoHTTPD.LOG.log(Level.SEVERE, "encoding problem, responding nothing", e);
            bytes = new byte[0];
        }
        return newFixedLengthResponse(status, contentType.getContentTypeHeader(), new ByteArrayInputStream(bytes), bytes.length);
    }
}
Also used : ContentType(org.nanohttpd.protocols.http.content.ContentType) ByteArrayInputStream(java.io.ByteArrayInputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CharsetEncoder(java.nio.charset.CharsetEncoder)

Aggregations

ContentType (org.nanohttpd.protocols.http.content.ContentType)3 BufferedWriter (java.io.BufferedWriter)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 DataOutput (java.io.DataOutput)1 DataOutputStream (java.io.DataOutputStream)1 IOException (java.io.IOException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 PrintWriter (java.io.PrintWriter)1 RandomAccessFile (java.io.RandomAccessFile)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ByteBuffer (java.nio.ByteBuffer)1 CharsetEncoder (java.nio.charset.CharsetEncoder)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 ResponseException (org.nanohttpd.protocols.http.NanoHTTPD.ResponseException)1