Search in sources :

Example 26 with Headers

use of com.amazonaws.services.s3.Headers in project GitTest by xiaoxige.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    testView = (TestView) findViewById(R.id.testView);
    testView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
        }
    });
    try {
        ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        String appMV = appInfo.metaData.getString("MTA_CHANNEL");
        Toast.makeText(MainActivity.this, "appMV = " + appMV, Toast.LENGTH_SHORT).show();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    simpleDraweeView = (SimpleDraweeView) findViewById(R.id.simpleDraweeView);
    testView.setProgress(100, false);
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            testView.setProgress(3, true);
        }
    }, 2000);
    GenericDraweeHierarchy hierarchy = simpleDraweeView.getHierarchy();
    RoundingParams roundingParams = new RoundingParams();
    roundingParams.setBorder(Color.RED, 10);
    roundingParams.setRoundAsCircle(true);
    hierarchy.setRoundingParams(roundingParams);
    simpleDraweeView.setHierarchy(hierarchy);
    ControllerListener listener = new BaseControllerListener() {

        @Override
        public void onFinalImageSet(String id, @Nullable Object imageInfo, @Nullable Animatable animatable) {
            super.onFinalImageSet(id, imageInfo, animatable);
        }
    };
    DraweeController controller = Fresco.newDraweeControllerBuilder().setUri(new Uri.Builder().scheme(UriUtil.LOCAL_RESOURCE_SCHEME).path(String.valueOf(R.mipmap.ic_launcher)).build()).setOldController(simpleDraweeView.getController()).setControllerListener(listener).build();
    simpleDraweeView.setController(controller);
    /**
     * 网络相关(retrofit+rxjava+rxlife+stetho)
     */
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.SECONDS).readTimeout(5000, TimeUnit.SECONDS).writeTimeout(5000, TimeUnit.SECONDS).addNetworkInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Headers headers = request.headers();
            Headers build = headers.newBuilder().add("version", "1.0").add("token", "xiaoxige").build();
            request = request.newBuilder().headers(build).build();
            Log.e("TAG", "url = " + request.url().uri().toString());
            String method = request.method();
            if (method.equals("GET") || method.equals("DELETE")) {
                HttpUrl url = request.url();
                HttpUrl httpUrl = url.newBuilder().addQueryParameter("xiaoxige", "one").addQueryParameter("zhuxiaoan", "two").build();
                request = request.newBuilder().url(httpUrl).build();
            } else {
                RequestBody body = request.body();
                if (body != null) {
                    Buffer buffer = new Buffer();
                    body.writeTo(buffer);
                    String readUtf8 = buffer.readUtf8();
                    // 可能需要对body进行加密
                    // TODO: 2017/11/3
                    RequestBody requestBody = RequestBody.create(body.contentType(), readUtf8);
                    request = request.newBuilder().method(method, requestBody).build();
                }
            }
            return chain.proceed(request);
        }
    }).addNetworkInterceptor(new StethoInterceptor()).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com").addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).client(client).build();
    final NetApi api = retrofit.create(NetApi.class);
    Flowable flowable = Flowable.create(new FlowableOnSubscribe<String>() {

        @Override
        public void subscribe(@NonNull FlowableEmitter<String> flowableEmitter) throws Exception {
            String response = MainActivity.execute(api.getBaiduWeb());
            if (TextUtils.isEmpty(response)) {
                flowableEmitter.onError(new Exception());
                return;
            }
            flowableEmitter.onNext(response);
            flowableEmitter.onComplete();
        }
    }, BackpressureStrategy.LATEST).compose(bindUntilEvent(ActivityEvent.DESTROY)).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io());
    flowable.subscribe(new XXGSubscriber<String>() {

        @Override
        public void xxgNext(String o) {
            super.xxgNext(o);
            Log.e("TAG", "o = " + o);
        }

        @Override
        public void xxgError(Throwable t) {
            super.xxgError(t);
            Log.e("TAG", "t = " + t.getMessage());
        }

        @Override
        public void xxgComplete() {
            super.xxgComplete();
            Log.e("TAG", "Complete");
        }
    });
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GenericDraweeHierarchy(com.facebook.drawee.generic.GenericDraweeHierarchy) DraweeController(com.facebook.drawee.interfaces.DraweeController) Headers(okhttp3.Headers) ApplicationInfo(android.content.pm.ApplicationInfo) Uri(android.net.Uri) PackageManager(android.content.pm.PackageManager) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) NonNull(io.reactivex.annotations.NonNull) FlowableEmitter(io.reactivex.FlowableEmitter) Interceptor(okhttp3.Interceptor) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) RoundingParams(com.facebook.drawee.generic.RoundingParams) RequestBody(okhttp3.RequestBody) Buffer(okio.Buffer) FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) Request(okhttp3.Request) Handler(android.os.Handler) ControllerListener(com.facebook.drawee.controller.ControllerListener) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) IOException(java.io.IOException) SimpleDraweeView(com.facebook.drawee.view.SimpleDraweeView) View(android.view.View) HttpUrl(okhttp3.HttpUrl) IOException(java.io.IOException) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Animatable(android.graphics.drawable.Animatable) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Nullable(javax.annotation.Nullable) Flowable(io.reactivex.Flowable)

Example 27 with Headers

use of com.amazonaws.services.s3.Headers in project Varis-Android by dkhmelenko.

the class BuildsDetailsPresenter method startLoadingLog.

/**
     * Starts loading log file
     *
     * @param jobId Job ID
     */
public void startLoadingLog(long jobId) {
    mJobId = jobId;
    String accessToken = AppSettings.getAccessToken();
    Single<String> responseSingle;
    if (TextUtils.isEmpty(accessToken)) {
        responseSingle = mRawClient.getApiService().getLog(String.valueOf(mJobId));
    } else {
        String auth = String.format("token %1$s", AppSettings.getAccessToken());
        responseSingle = mRawClient.getApiService().getLog(auth, String.valueOf(mJobId));
    }
    Disposable subscription = responseSingle.subscribeOn(Schedulers.io()).map(s -> mRawClient.getLogUrl(mJobId)).onErrorResumeNext(new Function<Throwable, SingleSource<String>>() {

        @Override
        public SingleSource<String> apply(@NonNull Throwable throwable) throws Exception {
            String redirectUrl = "";
            HttpException httpException = (HttpException) throwable;
            Headers headers = httpException.response().headers();
            for (String header : headers.names()) {
                if (header.equals("Location")) {
                    redirectUrl = headers.get(header);
                    break;
                }
            }
            return Single.just(redirectUrl);
        }
    }).retry(LOAD_LOG_MAX_ATTEMPT).observeOn(AndroidSchedulers.mainThread()).subscribe((logUrl, throwable) -> {
        if (throwable == null) {
            getView().setLogUrl(logUrl);
        } else {
            getView().showLogError();
            getView().showLoadingError(throwable.getMessage());
        }
    });
    mSubscriptions.add(subscription);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) Headers(okhttp3.Headers) NonNull(io.reactivex.annotations.NonNull) HttpException(retrofit2.HttpException)

Example 28 with Headers

use of com.amazonaws.services.s3.Headers in project Varis-Android by dkhmelenko.

the class BuildsDetailsPresenter method startLoadingLog.

/**
 * Starts loading log file
 *
 * @param jobId Job ID
 */
public void startLoadingLog(long jobId) {
    mJobId = jobId;
    String accessToken = mAppSettings.getAccessToken();
    Single<String> responseSingle;
    if (StringUtils.isEmpty(accessToken)) {
        responseSingle = mRawClient.getApiService().getLog(String.valueOf(mJobId));
    } else {
        String auth = String.format("token %1$s", mAppSettings.getAccessToken());
        responseSingle = mRawClient.getApiService().getLog(auth, String.valueOf(mJobId));
    }
    Disposable subscription = responseSingle.subscribeOn(Schedulers.io()).map(s -> mRawClient.getLogUrl(mJobId)).onErrorResumeNext(new Function<Throwable, SingleSource<String>>() {

        @Override
        public SingleSource<String> apply(@NonNull Throwable throwable) throws Exception {
            String redirectUrl = "";
            if (throwable instanceof HttpException) {
                HttpException httpException = (HttpException) throwable;
                Headers headers = httpException.response().headers();
                for (String header : headers.names()) {
                    if (header.equals("Location")) {
                        redirectUrl = headers.get(header);
                        break;
                    }
                }
                return Single.just(redirectUrl);
            } else {
                return Single.error(throwable);
            }
        }
    }).retry(LOAD_LOG_MAX_ATTEMPT).map(mRawClient::singleStringRequest).map(response -> mLogsParser.parseLog(response.blockingGet())).observeOn(AndroidSchedulers.mainThread()).subscribe((log, throwable) -> {
        if (throwable == null) {
            getView().setLog(log);
        } else {
            getView().showLogError();
            getView().showLoadingError(throwable.getMessage());
        }
    });
    mSubscriptions.add(subscription);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) Headers(okhttp3.Headers) NonNull(io.reactivex.annotations.NonNull) HttpException(retrofit2.HttpException)

Example 29 with Headers

use of com.amazonaws.services.s3.Headers in project mobile-sdk-android by meniga.

the class MenigaHttpLogger method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (logLevel == LogLevel.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = logType == LogType.BODY_ONLY || logType == LogType.BODY_AND_HEADERS;
    boolean logHeaders = logType == LogType.HEADERS_ONLY || logType == LogType.BODY_AND_HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    String reqUrl = request.url().toString();
    String requestStartMessage = request.method() + REQUEST_START + reqUrl;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so their values are known.
            if (requestBody.contentType() != null) {
                log(getHeaderString("Content-Type", requestBody.contentType().toString()));
            }
            if (requestBody.contentLength() != -1) {
                log(getHeaderString("Content-Length", Long.toString(requestBody.contentLength())));
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                log(getHeaderString(name, headers.value(i)));
            }
        }
    }
    if (!logBody) {
        log(REQUEST_END + request.method());
    } else if (!hasRequestBody) {
        log(BODY);
        log(NO_BODY);
    } else if (bodyEncoded(request.headers())) {
        log(REQUEST_END + request.method() + " (encoded body omitted)");
    } else {
        Buffer buffer = new Buffer();
        try {
            requestBody.writeTo(buffer);
        } catch (ConcurrentModificationException ex) {
            log("Error logging body - got ConcurrentModificationException");
        }
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        log(BODY);
        if (isPlaintext(buffer)) {
            log(buffer.readString(charset));
            log(REQUEST_END + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        } else {
            log("<" + requestBody.contentLength() + "-BYTE BINARY BODY OMITTED");
            log(REQUEST_END + request.method());
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log("<---- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    log(RESPONSE_START + reqUrl);
    log("(" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ")");
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            log(getHeaderString(headers.name(i), headers.value(i)));
        }
    }
    if (!logBody) {
        log(RESPONSE_END);
    } else if (!HttpHeaders.hasBody(response)) {
        log(BODY);
        log(NO_BODY);
        log(RESPONSE_END);
    } else if (bodyEncoded(response.headers())) {
        log(BODY);
        log("<ENCODED BODY OMITTED>");
        log(RESPONSE_END);
    } else {
        BufferedSource source = responseBody.source();
        // Buffer the entire body.
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                log(BODY);
                log("<ERROR DECODING BODY; CHARSET IS LIKELY MALFORMED.>");
                log(RESPONSE_END);
                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            log(BODY);
            log("<BINARY " + buffer.size() + "-BYTE BODY OMITTED>");
            log(RESPONSE_END);
            return response;
        }
        if (contentLength != 0) {
            log(BODY + " (" + buffer.size() + "-byte body)");
            log(buffer.clone().readString(charset));
        }
        log(RESPONSE_END);
    }
    return response;
}
Also used : Buffer(okio.Buffer) ConcurrentModificationException(java.util.ConcurrentModificationException) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ConcurrentModificationException(java.util.ConcurrentModificationException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 30 with Headers

use of com.amazonaws.services.s3.Headers in project oap by oaplatform.

the class Client method uploadFile.

@SneakyThrows
public Response uploadFile(String uri, String prefix, Path path) {
    final ContentType contentType = ContentType.create(java.nio.file.Files.probeContentType(path));
    OkHttpClient client = new OkHttpClient();
    final MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("upfile", path.toFile().getName(), RequestBody.create(MediaType.parse(contentType.toString()), path.toFile())).addFormDataPart("prefix", prefix).build();
    okhttp3.Request request = new okhttp3.Request.Builder().url(uri).post(body).build();
    final okhttp3.Response response = client.newCall(request).execute();
    final Headers headers = response.headers();
    final java.util.stream.Stream<String> stream = headers.names().stream();
    final Map<String, String> h = stream.collect(Collectors.toMap(n -> n, headers::get));
    return new Response(response.code(), response.message(), h, Optional.ofNullable(response.body().contentType()).map(mt -> ContentType.create(mt.type() + "/" + mt.subtype(), mt.charset())), response.body().bytes());
}
Also used : Binder(oap.json.Binder) HttpPost(org.apache.http.client.methods.HttpPost) SSLContext(javax.net.ssl.SSLContext) Arrays(java.util.Arrays) BufferedInputStream(java.io.BufferedInputStream) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) SneakyThrows(lombok.SneakyThrows) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) Maps(oap.util.Maps) Date(java.util.Date) TimeoutException(java.util.concurrent.TimeoutException) RequestConfig(org.apache.http.client.config.RequestConfig) HttpAsyncClients(org.apache.http.impl.nio.client.HttpAsyncClients) Header(org.apache.http.Header) HTTP_NOT_MODIFIED(java.net.HttpURLConnection.HTTP_NOT_MODIFIED) SSLIOSessionStrategy(org.apache.http.nio.conn.ssl.SSLIOSessionStrategy) Future(java.util.concurrent.Future) SSLContexts(org.apache.http.ssl.SSLContexts) Map(java.util.Map) ToString(lombok.ToString) TypeRef(oap.reflect.TypeRef) NoopIOSessionStrategy(org.apache.http.nio.conn.NoopIOSessionStrategy) URI(java.net.URI) Stream(oap.util.Stream) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) Closeables(oap.io.Closeables) PoolingNHttpClientConnectionManager(org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) ProgressInputStream.progress(oap.io.ProgressInputStream.progress) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) KeyStore(java.security.KeyStore) PublicSuffixMatcherLoader(org.apache.http.conn.util.PublicSuffixMatcherLoader) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Slf4j(lombok.extern.slf4j.Slf4j) Try(oap.util.Try) List(java.util.List) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) MultipartBody(okhttp3.MultipartBody) HttpGet(org.apache.http.client.methods.HttpGet) ByteStreams(com.google.common.io.ByteStreams) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) Optional(java.util.Optional) NameValuePair(org.apache.http.NameValuePair) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Pair(oap.util.Pair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) DateUtils(org.apache.http.client.utils.DateUtils) RegistryBuilder(org.apache.http.config.RegistryBuilder) Pair.__(oap.util.Pair.__) Files(oap.io.Files) CookieSpecs(org.apache.http.client.config.CookieSpecs) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Headers(okhttp3.Headers) RequestBody(okhttp3.RequestBody) HTTP_OK(java.net.HttpURLConnection.HTTP_OK) HttpDelete(org.apache.http.client.methods.HttpDelete) Collectors.toMap(oap.util.Maps.Collectors.toMap) Cookie(org.apache.http.cookie.Cookie) StringUtils.split(org.apache.commons.lang3.StringUtils.split) SchemeIOSessionStrategy(org.apache.http.nio.conn.SchemeIOSessionStrategy) lombok.val(lombok.val) AsyncCallbacks(oap.concurrent.AsyncCallbacks) FutureCallback(org.apache.http.concurrent.FutureCallback) IOException(java.io.IOException) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) Consumer(java.util.function.Consumer) IOReactorException(org.apache.http.nio.reactor.IOReactorException) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) HTTP_MOVED_TEMP(java.net.HttpURLConnection.HTTP_MOVED_TEMP) OkHttpClient(okhttp3.OkHttpClient) HttpPut(org.apache.http.client.methods.HttpPut) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) IoStreams(oap.io.IoStreams) PLAIN(oap.io.IoStreams.Encoding.PLAIN) Closeable(java.io.Closeable) HttpResponse(org.apache.http.HttpResponse) InputStreamEntity(org.apache.http.entity.InputStreamEntity) InputStream(java.io.InputStream) APPLICATION_OCTET_STREAM(org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM) OkHttpClient(okhttp3.OkHttpClient) ContentType(org.apache.http.entity.ContentType) Headers(okhttp3.Headers) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) RegistryBuilder(org.apache.http.config.RegistryBuilder) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ToString(lombok.ToString) HttpResponse(org.apache.http.HttpResponse) MultipartBody(okhttp3.MultipartBody) SneakyThrows(lombok.SneakyThrows)

Aggregations

Headers (okhttp3.Headers)128 Request (okhttp3.Request)61 Response (okhttp3.Response)54 Test (org.junit.Test)40 IOException (java.io.IOException)32 Call (okhttp3.Call)30 RequestBody (okhttp3.RequestBody)25 CancelledException (com.hippo.ehviewer.client.exception.CancelledException)20 EhException (com.hippo.ehviewer.client.exception.EhException)20 NoHAtHClientException (com.hippo.ehviewer.client.exception.NoHAtHClientException)20 ParseException (com.hippo.ehviewer.client.exception.ParseException)20 StatusCodeException (com.hippo.network.StatusCodeException)20 ResponseBody (okhttp3.ResponseBody)18 HttpHeaders (okhttp3.internal.http.HttpHeaders)18 MediaType (okhttp3.MediaType)15 ServiceResponseWithHeaders (com.microsoft.rest.ServiceResponseWithHeaders)14 HeaderResponseBoolHeaders (fixtures.header.models.HeaderResponseBoolHeaders)14 HeaderResponseByteHeaders (fixtures.header.models.HeaderResponseByteHeaders)14 HeaderResponseDateHeaders (fixtures.header.models.HeaderResponseDateHeaders)14 HeaderResponseDatetimeHeaders (fixtures.header.models.HeaderResponseDatetimeHeaders)14