Search in sources :

Example 1 with AsyncHttpRequestBody

use of com.koushikdutta.async.http.body.AsyncHttpRequestBody in project ion by koush.

the class IonRequestBuilder method getLoaderEmitter.

private <T> void getLoaderEmitter(final EmitterTransform<T> ret, AsyncHttpRequest request) {
    if (body != null && (uploadProgressHandler != null || uploadProgressBar != null || uploadProgress != null || uploadProgressDialog != null)) {
        AsyncHttpRequestBody wrappedBody = new RequestBodyUploadObserver(body, new ProgressCallback() {

            @Override
            public void onProgress(final long downloaded, final long total) {
                assert Thread.currentThread() != Looper.getMainLooper().getThread();
                final int percent = (int) ((float) downloaded / total * 100f);
                if (uploadProgressBar != null)
                    uploadProgressBar.setProgress(percent);
                if (uploadProgressDialog != null)
                    uploadProgressDialog.setProgress(percent);
                if (uploadProgress != null)
                    uploadProgress.onProgress(downloaded, total);
                if (uploadProgressHandler != null) {
                    AsyncServer.post(Ion.mainHandler, new Runnable() {

                        @Override
                        public void run() {
                            if (ret.isCancelled() || ret.isDone())
                                return;
                            uploadProgressHandler.onProgress(downloaded, total);
                        }
                    });
                }
            }
        });
        request.setBody(wrappedBody);
    }
    resolveAndLoadRequest(request, ret);
}
Also used : AsyncHttpRequestBody(com.koushikdutta.async.http.body.AsyncHttpRequestBody)

Example 2 with AsyncHttpRequestBody

use of com.koushikdutta.async.http.body.AsyncHttpRequestBody in project AndroidAsync by koush.

the class HttpTransportMiddleware method exchangeHeaders.

@Override
public boolean exchangeHeaders(final OnExchangeHeaderData data) {
    Protocol p = Protocol.get(data.protocol);
    if (p != null && p != Protocol.HTTP_1_0 && p != Protocol.HTTP_1_1)
        return super.exchangeHeaders(data);
    AsyncHttpRequest request = data.request;
    AsyncHttpRequestBody requestBody = data.request.getBody();
    if (requestBody != null) {
        if (requestBody.length() >= 0) {
            request.getHeaders().set("Content-Length", String.valueOf(requestBody.length()));
            data.response.sink(data.socket);
        } else if ("close".equals(request.getHeaders().get("Connection"))) {
            data.response.sink(data.socket);
        } else {
            request.getHeaders().set("Transfer-Encoding", "Chunked");
            data.response.sink(new ChunkedOutputFilter(data.socket));
        }
    }
    String rl = request.getRequestLine().toString();
    String rs = request.getHeaders().toPrefixString(rl);
    byte[] rsBytes = rs.getBytes();
    // try to get the request body in the same packet as the request headers... if it will fit
    // in the max MTU (1540 or whatever).
    final boolean waitForBody = requestBody != null && requestBody.length() >= 0 && requestBody.length() + rsBytes.length < 1024;
    final BufferedDataSink bsink;
    final DataSink headerSink;
    if (waitForBody) {
        // force buffering of headers
        bsink = new BufferedDataSink(data.response.sink());
        bsink.forceBuffering(true);
        data.response.sink(bsink);
        headerSink = bsink;
    } else {
        bsink = null;
        headerSink = data.socket;
    }
    request.logv("\n" + rs);
    final CompletedCallback sentCallback = data.sendHeadersCallback;
    Util.writeAll(headerSink, rsBytes, new CompletedCallback() {

        @Override
        public void onCompleted(Exception ex) {
            Util.end(sentCallback, ex);
            // flush headers and any request body that was written by the callback
            if (bsink != null) {
                bsink.forceBuffering(false);
                bsink.setMaxBuffer(0);
            }
        }
    });
    LineEmitter.StringCallback headerCallback = new LineEmitter.StringCallback() {

        Headers mRawHeaders = new Headers();

        String statusLine;

        @Override
        public void onStringAvailable(String s) {
            try {
                s = s.trim();
                if (statusLine == null) {
                    statusLine = s;
                } else if (!TextUtils.isEmpty(s)) {
                    mRawHeaders.addLine(s);
                } else {
                    String[] parts = statusLine.split(" ", 3);
                    if (parts.length < 2)
                        throw new Exception(new IOException("Not HTTP"));
                    data.response.headers(mRawHeaders);
                    String protocol = parts[0];
                    data.response.protocol(protocol);
                    data.response.code(Integer.parseInt(parts[1]));
                    data.response.message(parts.length == 3 ? parts[2] : "");
                    data.receiveHeadersCallback.onCompleted(null);
                    // socket may get detached after headers (websocket)
                    AsyncSocket socket = data.response.socket();
                    if (socket == null)
                        return;
                    DataEmitter emitter;
                    // return content length, etc, which will confuse the body decoder
                    if (AsyncHttpHead.METHOD.equalsIgnoreCase(data.request.getMethod())) {
                        emitter = HttpUtil.EndEmitter.create(socket.getServer(), null);
                    } else {
                        emitter = HttpUtil.getBodyDecoder(socket, Protocol.get(protocol), mRawHeaders, false);
                    }
                    data.response.emitter(emitter);
                }
            } catch (Exception ex) {
                data.receiveHeadersCallback.onCompleted(ex);
            }
        }
    };
    LineEmitter liner = new LineEmitter();
    data.socket.setDataCallback(liner);
    liner.setLineCallback(headerCallback);
    return true;
}
Also used : BufferedDataSink(com.koushikdutta.async.BufferedDataSink) DataSink(com.koushikdutta.async.DataSink) CompletedCallback(com.koushikdutta.async.callback.CompletedCallback) BufferedDataSink(com.koushikdutta.async.BufferedDataSink) IOException(java.io.IOException) ChunkedOutputFilter(com.koushikdutta.async.http.filter.ChunkedOutputFilter) IOException(java.io.IOException) AsyncSocket(com.koushikdutta.async.AsyncSocket) LineEmitter(com.koushikdutta.async.LineEmitter) DataEmitter(com.koushikdutta.async.DataEmitter) AsyncHttpRequestBody(com.koushikdutta.async.http.body.AsyncHttpRequestBody)

Example 3 with AsyncHttpRequestBody

use of com.koushikdutta.async.http.body.AsyncHttpRequestBody in project AndroidAsync by koush.

the class SpdyMiddleware method exchangeHeaders.

@Override
public boolean exchangeHeaders(final OnExchangeHeaderData data) {
    if (!(data.socket instanceof AsyncSpdyConnection.SpdySocket))
        return super.exchangeHeaders(data);
    AsyncHttpRequestBody requestBody = data.request.getBody();
    if (requestBody != null) {
        data.response.sink(data.socket);
    }
    // headers were already sent as part of the socket being opened.
    data.sendHeadersCallback.onCompleted(null);
    final AsyncSpdyConnection.SpdySocket spdySocket = (AsyncSpdyConnection.SpdySocket) data.socket;
    spdySocket.headers().then(new TransformFuture<Headers, List<Header>>() {

        @Override
        protected void transform(List<Header> result) throws Exception {
            Headers headers = new Headers();
            for (Header header : result) {
                String key = header.name.utf8();
                String value = header.value.utf8();
                headers.add(key, value);
            }
            String status = headers.remove(Header.RESPONSE_STATUS.utf8());
            String[] statusParts = status.split(" ", 2);
            data.response.code(Integer.parseInt(statusParts[0]));
            if (statusParts.length == 2)
                data.response.message(statusParts[1]);
            data.response.protocol(headers.remove(Header.VERSION.utf8()));
            data.response.headers(headers);
            setComplete(headers);
        }
    }).setCallback(new FutureCallback<Headers>() {

        @Override
        public void onCompleted(Exception e, Headers result) {
            data.receiveHeadersCallback.onCompleted(e);
            DataEmitter emitter = HttpUtil.getBodyDecoder(spdySocket, spdySocket.getConnection().protocol, result, false);
            data.response.emitter(emitter);
        }
    });
    return true;
}
Also used : Headers(com.koushikdutta.async.http.Headers) IOException(java.io.IOException) DataEmitter(com.koushikdutta.async.DataEmitter) ArrayList(java.util.ArrayList) ByteBufferList(com.koushikdutta.async.ByteBufferList) List(java.util.List) AsyncHttpRequestBody(com.koushikdutta.async.http.body.AsyncHttpRequestBody) TransformFuture(com.koushikdutta.async.future.TransformFuture)

Example 4 with AsyncHttpRequestBody

use of com.koushikdutta.async.http.body.AsyncHttpRequestBody in project AndroidAsync by koush.

the class SpdyMiddleware method newSocket.

private void newSocket(GetSocketData data, final AsyncSpdyConnection connection, final ConnectCallback callback) {
    final AsyncHttpRequest request = data.request;
    data.protocol = connection.protocol.toString();
    final AsyncHttpRequestBody requestBody = data.request.getBody();
    // this causes app engine to shit a brick, but if it is missing,
    // drive shits the bed
    //        if (requestBody != null) {
    //            if (requestBody.length() >= 0) {
    //                request.getHeaders().set("Content-Length", String.valueOf(requestBody.length()));
    //            }
    //        }
    final ArrayList<Header> headers = new ArrayList<Header>();
    headers.add(new Header(Header.TARGET_METHOD, request.getMethod()));
    headers.add(new Header(Header.TARGET_PATH, requestPath(request.getUri())));
    String host = request.getHeaders().get("Host");
    if (Protocol.SPDY_3 == connection.protocol) {
        headers.add(new Header(Header.VERSION, "HTTP/1.1"));
        headers.add(new Header(Header.TARGET_HOST, host));
    } else if (Protocol.HTTP_2 == connection.protocol) {
        // Optional in HTTP/2
        headers.add(new Header(Header.TARGET_AUTHORITY, host));
    } else {
        throw new AssertionError();
    }
    headers.add(new Header(Header.TARGET_SCHEME, request.getUri().getScheme()));
    final Multimap mm = request.getHeaders().getMultiMap();
    for (String key : mm.keySet()) {
        if (SpdyTransport.isProhibitedHeader(connection.protocol, key))
            continue;
        for (String value : mm.get(key)) {
            headers.add(new Header(key.toLowerCase(Locale.US), value));
        }
    }
    request.logv("\n" + request);
    final AsyncSpdyConnection.SpdySocket spdy = connection.newStream(headers, requestBody != null, true);
    callback.onConnectCompleted(null, spdy);
}
Also used : Multimap(com.koushikdutta.async.http.Multimap) ArrayList(java.util.ArrayList) AsyncHttpRequestBody(com.koushikdutta.async.http.body.AsyncHttpRequestBody) AsyncHttpRequest(com.koushikdutta.async.http.AsyncHttpRequest)

Aggregations

AsyncHttpRequestBody (com.koushikdutta.async.http.body.AsyncHttpRequestBody)4 DataEmitter (com.koushikdutta.async.DataEmitter)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 AsyncSocket (com.koushikdutta.async.AsyncSocket)1 BufferedDataSink (com.koushikdutta.async.BufferedDataSink)1 ByteBufferList (com.koushikdutta.async.ByteBufferList)1 DataSink (com.koushikdutta.async.DataSink)1 LineEmitter (com.koushikdutta.async.LineEmitter)1 CompletedCallback (com.koushikdutta.async.callback.CompletedCallback)1 TransformFuture (com.koushikdutta.async.future.TransformFuture)1 AsyncHttpRequest (com.koushikdutta.async.http.AsyncHttpRequest)1 Headers (com.koushikdutta.async.http.Headers)1 Multimap (com.koushikdutta.async.http.Multimap)1 ChunkedOutputFilter (com.koushikdutta.async.http.filter.ChunkedOutputFilter)1 List (java.util.List)1