Search in sources :

Example 1 with MaybeEmitter

use of io.reactivex.MaybeEmitter in project NetDiscovery by fengzhizi715.

the class OkHttpDownloader method download.

@Override
public Maybe<Response> download(Request request) {
    okhttp3.Request.Builder requestBuilder = null;
    if (request.getHttpMethod() == HttpMethod.GET) {
        requestBuilder = new okhttp3.Request.Builder().url(request.getUrl());
    } else if (request.getHttpMethod() == HttpMethod.POST) {
        HttpRequestBody httpRequestBody = request.getHttpRequestBody();
        if (httpRequestBody != null) {
            MediaType mediaType = MediaType.parse(httpRequestBody.getContentType());
            // 创建RequestBody对象,将参数按照指定的MediaType封装
            RequestBody requestBody = RequestBody.create(mediaType, httpRequestBody.getBody());
            requestBuilder = new okhttp3.Request.Builder().url(request.getUrl()).post(requestBody);
        }
    }
    if (request.getHeader() != null) {
        for (Map.Entry<String, String> entry : request.getHeader().entrySet()) {
            requestBuilder.addHeader(entry.getKey(), entry.getValue());
        }
    }
    // 针对post请求,需要对header添加一些信息
    if (request.getHttpMethod() == HttpMethod.POST) {
        if (Preconditions.isNotBlank(request.getHttpRequestBody()) && Preconditions.isNotBlank(request.getHttpRequestBody().getContentType())) {
            requestBuilder.addHeader("Content-type", request.getHttpRequestBody().getContentType());
        }
    }
    okhttp3.Request okrequest = requestBuilder.build();
    return Maybe.create(new MaybeOnSubscribe<okhttp3.Response>() {

        @Override
        public void subscribe(MaybeEmitter emitter) throws Exception {
            emitter.onSuccess(client.newCall(okrequest).execute());
        }
    }).map(new Function<okhttp3.Response, Response>() {

        @Override
        public Response apply(okhttp3.Response resp) throws Exception {
            Response response = new Response();
            response.setContent(resp.body().bytes());
            response.setStatusCode(resp.code());
            response.setContentType(resp.header("Content-Type"));
            return response;
        }
    });
}
Also used : MaybeEmitter(io.reactivex.MaybeEmitter) Request(com.cv4j.netdiscovery.core.domain.Request) IOException(java.io.IOException) Response(com.cv4j.netdiscovery.core.domain.Response) HttpRequestBody(com.cv4j.netdiscovery.core.domain.HttpRequestBody) MediaType(okhttp3.MediaType) MaybeOnSubscribe(io.reactivex.MaybeOnSubscribe) Map(java.util.Map) RequestBody(okhttp3.RequestBody) HttpRequestBody(com.cv4j.netdiscovery.core.domain.HttpRequestBody)

Example 2 with MaybeEmitter

use of io.reactivex.MaybeEmitter in project NetDiscovery by fengzhizi715.

the class FileDownloader method download.

@Override
public Maybe<Response> download(final Request request) {
    try {
        url = new URL(request.getUrl());
        // 将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
        // 此时cnnection只是为一个连接对象,待连接中
        httpUrlConnection = (HttpURLConnection) url.openConnection();
        // 设置是否要从 URL连接读取数据,默认为true
        httpUrlConnection.setDoInput(true);
        // 建立连接
        // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
        httpUrlConnection.connect();
        return Maybe.create(new MaybeOnSubscribe<InputStream>() {

            @Override
            public void subscribe(MaybeEmitter emitter) throws Exception {
                emitter.onSuccess(httpUrlConnection.getInputStream());
            }
        }).map(new Function<InputStream, Response>() {

            @Override
            public Response apply(InputStream inputStream) throws Exception {
                ByteArrayOutputStream baos = Utils.cloneInputStream(inputStream);
                // 只针对小的文件使用,大型的文件不建议这样使用
                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                Response response = new Response();
                response.setIs(is);
                response.setStatusCode(httpUrlConnection.getResponseCode());
                response.setContentType(httpUrlConnection.getContentType());
                return response;
            }
        });
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : Response(com.cv4j.netdiscovery.core.domain.Response) MalformedURLException(java.net.MalformedURLException) MaybeEmitter(io.reactivex.MaybeEmitter) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MaybeOnSubscribe(io.reactivex.MaybeOnSubscribe) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 3 with MaybeEmitter

use of io.reactivex.MaybeEmitter in project NetDiscovery by fengzhizi715.

the class UrlConnectionDownloader method download.

@Override
public Maybe<Response> download(Request request) {
    try {
        url = new URL(request.getUrl());
        // 设置Proxy
        if (request.getProxy() != null) {
            httpUrlConnection = (HttpURLConnection) url.openConnection(request.getProxy().toJavaNetProxy());
        } else {
            httpUrlConnection = (HttpURLConnection) url.openConnection();
        }
        // 使用Post请求时,设置Post body
        if (request.getHttpMethod() == HttpMethod.POST) {
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setRequestMethod("POST");
            // post 请求不用缓存
            httpUrlConnection.setUseCaches(false);
            if (request.getHttpRequestBody() != null) {
                httpUrlConnection.setRequestProperty("Content-Type", request.getHttpRequestBody().getContentType());
                OutputStream os = httpUrlConnection.getOutputStream();
                os.write(request.getHttpRequestBody().getBody());
                os.flush();
                os.close();
            }
        }
        // 设置请求头header
        if (Preconditions.isNotBlank(request.getHeader())) {
            for (Map.Entry<String, String> entry : request.getHeader().entrySet()) {
                httpUrlConnection.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        // 设置字符集
        if (Preconditions.isNotBlank(request.getCharset())) {
            httpUrlConnection.setRequestProperty("Accept-Charset", request.getCharset());
        }
        httpUrlConnection.connect();
        return Maybe.create(new MaybeOnSubscribe<InputStream>() {

            @Override
            public void subscribe(MaybeEmitter<InputStream> emitter) throws Exception {
                emitter.onSuccess(httpUrlConnection.getInputStream());
            }
        }).map(new Function<InputStream, Response>() {

            @Override
            public Response apply(InputStream inputStream) throws Exception {
                Response response = new Response();
                response.setContent(IOUtils.readInputStream(inputStream));
                response.setStatusCode(httpUrlConnection.getResponseCode());
                response.setContentType(httpUrlConnection.getContentType());
                if (request.isSaveCookie()) {
                    // save cookies
                    if (Preconditions.isNotBlank(httpUrlConnection.getHeaderField(Constant.SET_COOKIES_HEADER))) {
                        CookieGroup cookieGroup = CookieManager.getInsatance().getCookieGroup(request.getUrlParser().getHost());
                        if (cookieGroup == null) {
                            cookieGroup = new CookieGroup(request.getUrlParser().getHost());
                            String cookieStr = httpUrlConnection.getHeaderField(Constant.SET_COOKIES_HEADER);
                            String[] segs = cookieStr.split(";");
                            if (Preconditions.isNotBlank(segs)) {
                                for (String seg : segs) {
                                    String[] pairs = seg.trim().split("\\=");
                                    if (pairs.length == 2) {
                                        cookieSet.add(new Cookie(pairs[0], pairs[1]));
                                    }
                                }
                            }
                            cookieGroup.putAllCookies(cookieSet);
                            CookieManager.getInsatance().addCookieGroup(cookieGroup);
                        } else {
                            String cookieStr = httpUrlConnection.getHeaderField(Constant.SET_COOKIES_HEADER);
                            String[] segs = cookieStr.split(";");
                            if (Preconditions.isNotBlank(segs)) {
                                for (String seg : segs) {
                                    String[] pairs = seg.trim().split("\\=");
                                    if (pairs.length == 2) {
                                        cookieSet.add(new Cookie(pairs[0], pairs[1]));
                                    }
                                }
                            }
                            cookieGroup.putAllCookies(cookieSet);
                        }
                    }
                }
                return response;
            }
        });
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : Cookie(com.cv4j.netdiscovery.core.cookies.Cookie) MalformedURLException(java.net.MalformedURLException) MaybeEmitter(io.reactivex.MaybeEmitter) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(com.cv4j.netdiscovery.core.domain.Response) CookieGroup(com.cv4j.netdiscovery.core.cookies.CookieGroup) MaybeOnSubscribe(io.reactivex.MaybeOnSubscribe) Map(java.util.Map)

Example 4 with MaybeEmitter

use of io.reactivex.MaybeEmitter in project kripton by xcesco.

the class BindKripton180RawInsertSelectDataSource method execute.

public <T> Maybe<T> execute(final MaybeTransaction<T> transaction) {
    MaybeOnSubscribe<T> emitter = new MaybeOnSubscribe<T>() {

        @Override
        public void subscribe(MaybeEmitter<T> emitter) {
            boolean needToOpened = !BindKripton180RawInsertSelectDataSource.this.isOpenInWriteMode();
            boolean success = false;
            @SuppressWarnings("resource") SQLiteDatabase connection = needToOpened ? openWritableDatabase() : database();
            DataSourceSingleThread currentDaoFactory = _daoFactorySingleThread.bindToThread();
            currentDaoFactory.onSessionOpened();
            try {
                connection.beginTransaction();
                if (transaction != null && TransactionResult.COMMIT == transaction.onExecute(currentDaoFactory, emitter)) {
                    connection.setTransactionSuccessful();
                    success = true;
                }
            // no onComplete;
            } catch (Throwable e) {
                Logger.error(e.getMessage());
                e.printStackTrace();
                emitter.onError(e);
                currentDaoFactory.onSessionClear();
            } finally {
                try {
                    connection.endTransaction();
                } catch (Throwable e) {
                }
                if (needToOpened) {
                    close();
                }
                if (success) {
                    currentDaoFactory.onSessionClosed();
                } else {
                    currentDaoFactory.onSessionClear();
                }
            }
            return;
        }
    };
    Maybe<T> result = Maybe.create(emitter);
    if (globalSubscribeOn != null)
        result.subscribeOn(globalSubscribeOn);
    if (globalObserveOn != null)
        result.observeOn(globalObserveOn);
    return result;
}
Also used : MaybeEmitter(io.reactivex.MaybeEmitter) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) MaybeOnSubscribe(io.reactivex.MaybeOnSubscribe)

Example 5 with MaybeEmitter

use of io.reactivex.MaybeEmitter in project kripton by xcesco.

the class BindKripton180BeanInsertSelectDataSource method execute.

public <T> Maybe<T> execute(final MaybeTransaction<T> transaction) {
    MaybeOnSubscribe<T> emitter = new MaybeOnSubscribe<T>() {

        @Override
        public void subscribe(MaybeEmitter<T> emitter) {
            boolean needToOpened = !BindKripton180BeanInsertSelectDataSource.this.isOpenInWriteMode();
            boolean success = false;
            @SuppressWarnings("resource") SQLiteDatabase connection = needToOpened ? openWritableDatabase() : database();
            DataSourceSingleThread currentDaoFactory = _daoFactorySingleThread.bindToThread();
            currentDaoFactory.onSessionOpened();
            try {
                connection.beginTransaction();
                if (transaction != null && TransactionResult.COMMIT == transaction.onExecute(currentDaoFactory, emitter)) {
                    connection.setTransactionSuccessful();
                    success = true;
                }
            // no onComplete;
            } catch (Throwable e) {
                Logger.error(e.getMessage());
                e.printStackTrace();
                emitter.onError(e);
                currentDaoFactory.onSessionClear();
            } finally {
                try {
                    connection.endTransaction();
                } catch (Throwable e) {
                }
                if (needToOpened) {
                    close();
                }
                if (success) {
                    currentDaoFactory.onSessionClosed();
                } else {
                    currentDaoFactory.onSessionClear();
                }
            }
            return;
        }
    };
    Maybe<T> result = Maybe.create(emitter);
    if (globalSubscribeOn != null)
        result.subscribeOn(globalSubscribeOn);
    if (globalObserveOn != null)
        result.observeOn(globalObserveOn);
    return result;
}
Also used : MaybeEmitter(io.reactivex.MaybeEmitter) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) MaybeOnSubscribe(io.reactivex.MaybeOnSubscribe)

Aggregations

MaybeEmitter (io.reactivex.MaybeEmitter)9 MaybeOnSubscribe (io.reactivex.MaybeOnSubscribe)9 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 Response (com.cv4j.netdiscovery.core.domain.Response)4 IOException (java.io.IOException)4 InputStream (java.io.InputStream)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 Map (java.util.Map)2 Cookie (com.cv4j.netdiscovery.core.cookies.Cookie)1 CookieGroup (com.cv4j.netdiscovery.core.cookies.CookieGroup)1 HttpRequestBody (com.cv4j.netdiscovery.core.domain.HttpRequestBody)1 Request (com.cv4j.netdiscovery.core.domain.Request)1 NonNull (io.reactivex.annotations.NonNull)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 OutputStream (java.io.OutputStream)1 MediaType (okhttp3.MediaType)1 RequestBody (okhttp3.RequestBody)1 HttpEntity (org.apache.http.HttpEntity)1