Example usage for org.apache.http.entity ByteArrayEntity getContentLength

List of usage examples for org.apache.http.entity ByteArrayEntity getContentLength

Introduction

In this page you can find the example usage for org.apache.http.entity ByteArrayEntity getContentLength.

Prototype

public long getContentLength() 

Source Link

Usage

From source file:com.jkoolcloud.jesl.net.http.apache.HttpMessageUtils.java

/**
 * Set HTTP message content//from  w w  w .j  av  a 2s.co  m
 *
 * @param message HTTP message
 * @param contentType contentType
 * @param content content bytes
 * @param contentEncoding content encoding
 * @throws IOException if error writing message content
 */
public static void setContent(HttpMessage message, String contentType, byte[] content, String contentEncoding)
        throws IOException {
    ByteArrayEntity httpContent = new ByteArrayEntity(content);
    if (!StringUtils.isEmpty(contentEncoding))
        httpContent.setContentEncoding(contentEncoding);
    message.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(httpContent.getContentLength()));
    if (!StringUtils.isEmpty(contentType))
        message.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
    setEntity(message, httpContent);
}

From source file:com.android.im.imps.HttpDataChannel.java

private void trySend(Primitive p) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {/*from   w w w .j  a v a 2s .  c o m*/
        mSerializer.serialize(p, out);
    } catch (SerializerException e) {
        mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.SERIALIZER_ERROR,
                "Internal serializer error, primitive: " + p.getType());
        out.close();
        return;
    }

    HttpPost req = new HttpPost(mPostUri);
    req.addHeader(mContentTypeHeader);
    if (mMsisdnHeader != null) {
        req.addHeader(mMsisdnHeader);
    }
    ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
    req.setEntity(entity);

    mLastActive = SystemClock.elapsedRealtime();
    if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) {
        long sendBytes = entity.getContentLength() + 176 /* approx. header length */;
        ImpsLog.log(mConnection.getLoginUserName() + " >> " + p.getType() + " HTTP payload approx. " + sendBytes
                + " bytes");
    }
    if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
        ImpsLog.dumpRawPacket(out.toByteArray());
        ImpsLog.dumpPrimitive(p);
    }

    HttpResponse res = mHttpClient.execute(req);
    StatusLine statusLine = res.getStatusLine();
    HttpEntity resEntity = res.getEntity();

    InputStream in = resEntity.getContent();

    if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
        Log.d(ImpsLog.PACKET_TAG, statusLine.toString());
        Header[] headers = res.getAllHeaders();
        for (Header h : headers) {
            Log.d(ImpsLog.PACKET_TAG, h.toString());
        }
        int len = (int) resEntity.getContentLength();
        if (len > 0) {
            byte[] content = new byte[len];
            int offset = 0;
            int bytesRead = 0;
            do {
                bytesRead = in.read(content, offset, len);
                offset += bytesRead;
                len -= bytesRead;
            } while (bytesRead > 0);
            in.close();
            ImpsLog.dumpRawPacket(content);
            in = new ByteArrayInputStream(content);
        }
    }

    try {
        if (statusLine.getStatusCode() != HttpURLConnection.HTTP_OK) {
            mTxManager.notifyErrorResponse(p.getTransactionID(), statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());
            return;
        }
        if (resEntity.getContentLength() == 0) {
            // empty responses are only valid for Polling-Request or
            // server initiated transactions
            if ((p.getTransactionMode() != TransactionMode.Response)
                    && !p.getType().equals(ImpsTags.Polling_Request)) {
                mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.ILLEGAL_SERVER_RESPONSE,
                        "bad response from server");
            }
            return;
        }

        Primitive response = mParser.parse(in);

        if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
            ImpsLog.dumpPrimitive(response);
        }

        if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) {
            long len = 2 + resEntity.getContentLength() + statusLine.toString().length() + 2;
            Header[] headers = res.getAllHeaders();
            for (Header header : headers) {
                len += header.getName().length() + header.getValue().length() + 4;
            }
            ImpsLog.log(mConnection.getLoginUserName() + " << " + response.getType() + " HTTP payload approx. "
                    + len + "bytes");
        }

        if (!mReceiveQueue.offer(response)) {
            // This is almost impossible for a LinkedBlockingQueue.
            // We don't even bother to assign an error code for it.
            mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.UNKNOWN_ERROR,
                    "receiving queue full");
        }
    } catch (ParserException e) {
        ImpsLog.logError(e);
        mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.PARSER_ERROR,
                "Parser error, received a bad response from server");
    } finally {
        //consume all the content so that the connection can be re-used.
        resEntity.consumeContent();
    }
}

From source file:android.webkit.cts.TestWebServer.java

/**
 * Create an empty response with the given status.
 *//*from   w  ww  . ja  va 2s  .c  o m*/
private HttpResponse createResponse(int status) {
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status, null);
    String reason = null;

    // This synchronized silences findbugs.
    synchronized (TestWebServer.class) {
        if (sReasons == null) {
            sReasons = new Hashtable<Integer, String>();
            sReasons.put(HttpStatus.SC_UNAUTHORIZED, "Unauthorized");
            sReasons.put(HttpStatus.SC_NOT_FOUND, "Not Found");
            sReasons.put(HttpStatus.SC_FORBIDDEN, "Forbidden");
            sReasons.put(HttpStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily");
        }
        // Fill in error reason. Avoid use of the ReasonPhraseCatalog, which is
        // Locale-dependent.
        reason = sReasons.get(status);
    }

    if (reason != null) {
        StringBuffer buf = new StringBuffer("<html><head><title>");
        buf.append(reason);
        buf.append("</title></head><body>");
        buf.append(reason);
        buf.append("</body></html>");
        ByteArrayEntity entity = createEntity(buf.toString().getBytes());
        response.setEntity(entity);
        response.setHeader("Content-Length", "" + entity.getContentLength());
    }
    return response;
}

From source file:android.webkit.cts.TestWebServer.java

/**
 * Generate a response to the given request.
 *
 * <p>Always executed on the background server thread.
 *
 * <p>If there is an action associated with the response, it will be executed inside of
 * this function.//from  w  w w  .  ja  va 2 s  .co m
 *
 * @throws InterruptedException
 */
private HttpResponse getResponse(HttpRequest request) throws InterruptedException {
    assert Thread.currentThread() == mServerThread : "getResponse called from non-server thread";

    RequestLine requestLine = request.getRequestLine();
    HttpResponse httpResponse = null;
    Log.i(TAG, requestLine.getMethod() + ": " + requestLine.getUri());
    String uriString = requestLine.getUri();
    URI uri = URI.create(uriString);
    String path = uri.getPath();

    Response response = null;
    synchronized (mLock) {
        response = mResponseMap.get(path);
    }
    if (path.equals(SHUTDOWN_PREFIX)) {
        httpResponse = createResponse(HttpStatus.SC_OK);
    } else if (response == null) {
        httpResponse = createResponse(HttpStatus.SC_NOT_FOUND);
    } else if (response.mIsNotFound) {
        httpResponse = createResponse(HttpStatus.SC_NOT_FOUND);
        servedResponseFor(path, request);
    } else if (response.mIsRedirect) {
        httpResponse = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
        for (Pair<String, String> header : response.mResponseHeaders) {
            httpResponse.addHeader(header.first, header.second);
        }
        servedResponseFor(path, request);
    } else {
        if (response.mResponseAction != null)
            response.mResponseAction.run();

        httpResponse = createResponse(HttpStatus.SC_OK);
        ByteArrayEntity entity = createEntity(response.mResponseData);
        httpResponse.setEntity(entity);
        httpResponse.setHeader("Content-Length", "" + entity.getContentLength());
        for (Pair<String, String> header : response.mResponseHeaders) {
            httpResponse.addHeader(header.first, header.second);
        }
        servedResponseFor(path, request);
    }
    StatusLine sl = httpResponse.getStatusLine();
    Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
    setDateHeaders(httpResponse);
    return httpResponse;
}

From source file:com.android.mms.service.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD./*w  w  w .  j  a  va  2s  . c om*/
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @param isProxySet If proxy is set
 * @param proxyHost The host of the proxy
 * @param proxyPort The port of the proxy
 * @param resolver The custom name resolver to use
 * @param useIpv6 If we should use IPv6 address when the HTTP client resolves the host name
 * @param mmsConfig The MmsConfig to use
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws com.android.mms.service.exception.MmsHttpException if HTTP request gets error response (&gt;=400)
 */
public static byte[] httpConnection(Context context, String url, byte[] pdu, int method, boolean isProxySet,
        String proxyHost, int proxyPort, NameResolver resolver, boolean useIpv6, MmsConfig.Overridden mmsConfig)
        throws MmsHttpException {
    final String methodString = getMethodString(method);
    Log.v(TAG,
            "HttpUtils: request param list\n" + "url=" + url + "\n" + "method=" + methodString + "\n"
                    + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort="
                    + proxyPort + "\n" + "size=" + (pdu != null ? pdu.length : 0));

    NetworkAwareHttpClient client = null;
    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        client = createHttpClient(context, resolver, useIpv6, mmsConfig);
        HttpRequest req = null;

        switch (method) {
        case HTTP_POST_METHOD:
            ByteArrayEntity entity = new ByteArrayEntity(pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);

        // UA Profile URL header
        String xWapProfileTagName = mmsConfig.getUaProfTagName();
        String xWapProfileUrl = mmsConfig.getUaProfUrl();
        if (xWapProfileUrl != null) {
            Log.v(TAG, "HttpUtils: xWapProfUrl=" + xWapProfileUrl);
            req.addHeader(xWapProfileTagName, xWapProfileUrl);
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value. And replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsNaiKey() with the users NAI(Network Access Identifier)
        // inside the value.
        String extraHttpParams = mmsConfig.getHttpParams();

        if (!TextUtils.isEmpty(extraHttpParams)) {
            // Parse the parameter list
            String paramList[] = extraHttpParams.split("\\|");
            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);
                if (splitPair.length == 2) {
                    final String name = splitPair[0].trim();
                    final String value = resolveMacro(context, splitPair[1].trim(), mmsConfig);
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, getCurrentAcceptLanguage(Locale.getDefault()));

        final HttpResponse response = client.execute(target, req);
        final StatusLine status = response.getStatusLine();
        final HttpEntity entity = response.getEntity();
        Log.d(TAG,
                "HttpUtils: status=" + status + " size=" + (entity != null ? entity.getContentLength() : -1));
        for (Header header : req.getAllHeaders()) {
            if (header != null) {
                Log.v(TAG, "HttpUtils: header " + header.getName() + "=" + header.getValue());
            }
        }
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.d(TAG, "HttpUtils: transfer encoding is chunked");
                    int bytesTobeRead = mmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "HttpUtils: error reading input stream", e);
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.d(TAG, "HttpUtils: Chunked response length " + offset);
                        } else {
                            Log.e(TAG, "HttpUtils: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            StringBuilder sb = new StringBuilder();
            if (body != null) {
                sb.append("response: text=").append(new String(body)).append('\n');
            }
            for (Header header : req.getAllHeaders()) {
                if (header != null) {
                    sb.append("req header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            for (Header header : response.getAllHeaders()) {
                if (header != null) {
                    sb.append("resp header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            Log.e(TAG,
                    "HttpUtils: error response -- \n" + "mStatusCode=" + status.getStatusCode() + "\n"
                            + "reason=" + status.getReasonPhrase() + "\n" + "url=" + url + "\n" + "method="
                            + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost
                            + "\n" + "proxyPort=" + proxyPort + (sb != null ? "\n" + sb.toString() : ""));
            throw new MmsHttpException(status.getReasonPhrase());
        }
        return body;
    } catch (IOException e) {
        Log.e(TAG, "HttpUtils: IO failure", e);
        throw new MmsHttpException(e);
    } catch (URISyntaxException e) {
        Log.e(TAG, "HttpUtils: invalid url " + url);
        throw new MmsHttpException("Invalid url " + url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:android.webkit.cts.CtsTestServer.java

/**
 * Generate a response to the given request.
 * @throws InterruptedException// w ww .  j  ava  2 s .  co  m
 * @throws IOException
 */
private HttpResponse getResponse(HttpRequest request) throws Exception {
    RequestLine requestLine = request.getRequestLine();
    HttpResponse response = null;
    String uriString = requestLine.getUri();
    Log.i(TAG, requestLine.getMethod() + ": " + uriString);

    synchronized (this) {
        mQueries.add(uriString);
        mLastRequestMap.put(uriString, request);
        if (request instanceof HttpEntityEnclosingRequest) {
            mRequestEntities.add(((HttpEntityEnclosingRequest) request).getEntity());
        }
    }

    if (requestLine.getMethod().equals("POST")) {
        HttpResponse responseOnPost = onPost(request);
        if (responseOnPost != null) {
            return responseOnPost;
        }
    }

    URI uri = URI.create(uriString);
    String path = uri.getPath();
    String query = uri.getQuery();
    if (path.equals(FAVICON_PATH)) {
        path = FAVICON_ASSET_PATH;
    }
    if (path.startsWith(DELAY_PREFIX)) {
        String delayPath = path.substring(DELAY_PREFIX.length() + 1);
        String delay = delayPath.substring(0, delayPath.indexOf('/'));
        path = delayPath.substring(delay.length());
        try {
            Thread.sleep(Integer.valueOf(delay));
        } catch (InterruptedException ignored) {
            // ignore
        }
    }
    if (path.startsWith(AUTH_PREFIX)) {
        // authentication required
        Header[] auth = request.getHeaders("Authorization");
        if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS))
                // This is a hack to make sure that loads to this url's will always
                // ask for authentication. This is what the test expects.
                && !path.endsWith("embedded_image.html")) {
            // fall through and serve content
            path = path.substring(AUTH_PREFIX.length());
        } else {
            // request authorization
            response = createResponse(HttpStatus.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
        }
    }
    if (path.startsWith(BINARY_PREFIX)) {
        List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
        int length = 0;
        String mimeType = null;
        try {
            for (NameValuePair pair : args) {
                String name = pair.getName();
                if (name.equals("type")) {
                    mimeType = pair.getValue();
                } else if (name.equals("length")) {
                    length = Integer.parseInt(pair.getValue());
                }
            }
            if (length > 0 && mimeType != null) {
                ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
                entity.setContentType(mimeType);
                response = createResponse(HttpStatus.SC_OK);
                response.setEntity(entity);
                response.addHeader("Content-Disposition", "attachment; filename=test.bin");
                response.addHeader("Content-Type", mimeType);
                response.addHeader("Content-Length", "" + length);
            } else {
                // fall through, return 404 at the end
            }
        } catch (Exception e) {
            // fall through, return 404 at the end
            Log.w(TAG, e);
        }
    } else if (path.startsWith(ASSET_PREFIX)) {
        path = path.substring(ASSET_PREFIX.length());
        // request for an asset file
        try {
            InputStream in;
            if (path.startsWith(RAW_PREFIX)) {
                String resourceName = path.substring(RAW_PREFIX.length());
                int id = mResources.getIdentifier(resourceName, "raw", mContext.getPackageName());
                if (id == 0) {
                    Log.w(TAG, "Can't find raw resource " + resourceName);
                    throw new IOException();
                }
                in = mResources.openRawResource(id);
            } else {
                in = mAssets.open(path);
            }
            response = createResponse(HttpStatus.SC_OK);
            InputStreamEntity entity = new InputStreamEntity(in, in.available());
            String mimeType = mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
            if (mimeType == null) {
                mimeType = "text/html";
            }
            entity.setContentType(mimeType);
            response.setEntity(entity);
            if (query == null || !query.contains(NOLENGTH_POSTFIX)) {
                response.setHeader("Content-Length", "" + entity.getContentLength());
            }
        } catch (IOException e) {
            response = null;
            // fall through, return 404 at the end
        }
    } else if (path.startsWith(REDIRECT_PREFIX)) {
        response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
        String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
        Log.i(TAG, "Redirecting to: " + location);
        response.addHeader("Location", location);
    } else if (path.equals(QUERY_REDIRECT_PATH)) {
        String location = Uri.parse(uriString).getQueryParameter("dest");
        if (location != null) {
            Log.i(TAG, "Redirecting to: " + location);
            response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
            response.addHeader("Location", location);
        }
    } else if (path.startsWith(COOKIE_PREFIX)) {
        /*
         * Return a page with a title containing a list of all incoming cookies,
         * separated by '|' characters. If a numeric 'count' value is passed in a cookie,
         * return a cookie with the value incremented by 1. Otherwise, return a cookie
         * setting 'count' to 0.
         */
        response = createResponse(HttpStatus.SC_OK);
        Header[] cookies = request.getHeaders("Cookie");
        Pattern p = Pattern.compile("count=(\\d+)");
        StringBuilder cookieString = new StringBuilder(100);
        cookieString.append(cookies.length);
        int count = 0;
        for (Header cookie : cookies) {
            cookieString.append("|");
            String value = cookie.getValue();
            cookieString.append(value);
            Matcher m = p.matcher(value);
            if (m.find()) {
                count = Integer.parseInt(m.group(1)) + 1;
            }
        }

        response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
        response.setEntity(createPage(cookieString.toString(), cookieString.toString()));
    } else if (path.startsWith(SET_COOKIE_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        Uri parsedUri = Uri.parse(uriString);
        String key = parsedUri.getQueryParameter("key");
        String value = parsedUri.getQueryParameter("value");
        String cookie = key + "=" + value;
        response.addHeader("Set-Cookie", cookie);
        response.setEntity(createPage(cookie, cookie));
    } else if (path.startsWith(LINKED_SCRIPT_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        String src = Uri.parse(uriString).getQueryParameter("url");
        String scriptTag = "<script src=\"" + src + "\"></script>";
        response.setEntity(createPage("LinkedScript", scriptTag));
    } else if (path.equals(USERAGENT_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        Header agentHeader = request.getFirstHeader("User-Agent");
        String agent = "";
        if (agentHeader != null) {
            agent = agentHeader.getValue();
        }
        response.setEntity(createPage(agent, agent));
    } else if (path.equals(TEST_DOWNLOAD_PATH)) {
        response = createTestDownloadResponse(Uri.parse(uriString));
    } else if (path.equals(SHUTDOWN_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        // We cannot close the socket here, because we need to respond.
        // Status must be set to OK, or else the test will fail due to
        // a RunTimeException.
    } else if (path.equals(APPCACHE_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        response.setEntity(createEntity("<!DOCTYPE HTML>" + "<html manifest=\"appcache.manifest\">" + "  <head>"
                + "    <title>Waiting</title>" + "    <script>"
                + "      function updateTitle(x) { document.title = x; }"
                + "      window.applicationCache.onnoupdate = "
                + "          function() { updateTitle(\"onnoupdate Callback\"); };"
                + "      window.applicationCache.oncached = "
                + "          function() { updateTitle(\"oncached Callback\"); };"
                + "      window.applicationCache.onupdateready = "
                + "          function() { updateTitle(\"onupdateready Callback\"); };"
                + "      window.applicationCache.onobsolete = "
                + "          function() { updateTitle(\"onobsolete Callback\"); };"
                + "      window.applicationCache.onerror = "
                + "          function() { updateTitle(\"onerror Callback\"); };" + "    </script>" + "  </head>"
                + "  <body onload=\"updateTitle('Loaded');\">AppCache test</body>" + "</html>"));
    } else if (path.equals(APPCACHE_MANIFEST_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        try {
            StringEntity entity = new StringEntity("CACHE MANIFEST");
            // This entity property is not used when constructing the response, (See
            // AbstractMessageWriter.write(), which is called by
            // AbstractHttpServerConnection.sendResponseHeader()) so we have to set this header
            // manually.
            // TODO: Should we do this for all responses from this server?
            entity.setContentType("text/cache-manifest");
            response.setEntity(entity);
            response.setHeader("Content-Type", "text/cache-manifest");
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, "Unexpected UnsupportedEncodingException");
        }
    }
    if (response == null) {
        response = createResponse(HttpStatus.SC_NOT_FOUND);
    }
    StatusLine sl = response.getStatusLine();
    Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
    setDateHeaders(response);
    return response;
}