Search in sources :

Example 21 with HttpRequest

use of com.azure.android.core.http.HttpRequest in project azure-sdk-for-android by Azure.

the class OkHttpAsyncHttpClient method send.

@Override
public void send(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
    okhttp3.Request.Builder okhttpRequestBuilder = new okhttp3.Request.Builder();
    okhttpRequestBuilder.url(httpRequest.getUrl());
    if (httpRequest.getHeaders() != null) {
        Map<String, String> headers = new HashMap<>();
        for (HttpHeader hdr : httpRequest.getHeaders()) {
            if (hdr.getValue() != null) {
                headers.put(hdr.getName(), hdr.getValue());
            }
        }
        okhttpRequestBuilder.headers(okhttp3.Headers.of(headers));
    } else {
        okhttpRequestBuilder.headers(okhttp3.Headers.of(new HashMap<>()));
    }
    if (httpRequest.getHttpMethod() == HttpMethod.GET) {
        okhttpRequestBuilder.get();
    } else if (httpRequest.getHttpMethod() == HttpMethod.HEAD) {
        okhttpRequestBuilder.head();
    } else {
        byte[] content = httpRequest.getBody();
        content = content == null ? new byte[0] : content;
        final String contentType = httpRequest.getHeaders().getValue("Content-Type");
        if (contentType == null) {
            okhttpRequestBuilder.method(httpRequest.getHttpMethod().toString(), RequestBody.create(null, content));
        } else {
            okhttpRequestBuilder.method(httpRequest.getHttpMethod().toString(), RequestBody.create(MediaType.parse(contentType), content));
        }
    }
    final okhttp3.Request okHttpRequest = okhttpRequestBuilder.build();
    final okhttp3.Call call = httpClient.newCall(okHttpRequest);
    final String onCancelId = (cancellationToken == CancellationToken.NONE) ? null : UUID.randomUUID().toString();
    if (onCancelId != null) {
        // Register an identifiable Runnable to run on cancellationToken.cancel().
        // 
        // This Runnable unregistered once the 'call' completes.
        // 
        // We don't want a cancel on cancellationToken to call call.cancel()
        // after the call completion (though call.cancel() after it's completion is nop).
        // 
        cancellationToken.registerOnCancel(onCancelId, () -> call.cancel());
    }
    call.enqueue(new okhttp3.Callback() {

        @Override
        public void onFailure(okhttp3.Call call, IOException error) {
            if (onCancelId != null) {
                cancellationToken.unregisterOnCancel(onCancelId);
            }
            httpCallback.onError(error);
        }

        @Override
        public void onResponse(okhttp3.Call call, Response response) {
            if (onCancelId != null) {
                cancellationToken.unregisterOnCancel(onCancelId);
            }
            httpCallback.onSuccess(new HttpResponse(httpRequest) {

                private final HttpHeaders headers = fromOkHttpHeaders(response.headers());

                private final ResponseBody responseBody = response.body();

                @Override
                public int getStatusCode() {
                    return response.code();
                }

                @Override
                public String getHeaderValue(String name) {
                    return this.headers.getValue(name);
                }

                @Override
                public HttpHeaders getHeaders() {
                    return this.headers;
                }

                @Override
                public InputStream getBody() {
                    if (this.responseBody == null) {
                        return new ByteArrayInputStream(new byte[0]);
                    } else {
                        return this.responseBody.byteStream();
                    }
                }

                @Override
                public byte[] getBodyAsByteArray() {
                    if (this.responseBody == null) {
                        return new byte[0];
                    } else {
                        try {
                            return this.responseBody.bytes();
                        } catch (IOException e) {
                            throw logger.logExceptionAsError(new RuntimeException(e));
                        }
                    }
                }

                @Override
                public String getBodyAsString() {
                    return bomAwareToString(this.getBodyAsByteArray(), headers.getValue("Content-Type"));
                }

                @Override
                public void close() {
                    if (this.responseBody != null) {
                        this.responseBody.close();
                    }
                }

                @Override
                public String getBodyAsString(Charset charset) {
                    return new String(this.getBodyAsByteArray(), charset);
                }

                private HttpHeaders fromOkHttpHeaders(Headers headers) {
                    HttpHeaders httpHeaders = new HttpHeaders();
                    for (String headerName : headers.names()) {
                        httpHeaders.put(headerName, headers.get(headerName));
                    }
                    return httpHeaders;
                }
            });
        }
    });
}
Also used : HttpHeaders(com.azure.android.core.http.HttpHeaders) HashMap(java.util.HashMap) HttpHeaders(com.azure.android.core.http.HttpHeaders) Headers(okhttp3.Headers) HttpRequest(com.azure.android.core.http.HttpRequest) HttpResponse(com.azure.android.core.http.HttpResponse) Charset(java.nio.charset.Charset) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) HttpResponse(com.azure.android.core.http.HttpResponse) Response(okhttp3.Response) HttpHeader(com.azure.android.core.http.HttpHeader) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 22 with HttpRequest

use of com.azure.android.core.http.HttpRequest in project azure-sdk-for-android by Azure.

the class AddDatePolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    HttpRequest httpRequest = chain.getRequest();
    httpRequest.getHeaders().put("Date", format.format(OffsetDateTime.now()));
    chain.processNextPolicy(httpRequest);
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest)

Example 23 with HttpRequest

use of com.azure.android.core.http.HttpRequest in project azure-sdk-for-android by Azure.

the class AddHeadersPolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    HttpRequest httpRequest = chain.getRequest();
    for (HttpHeader header : headers) {
        httpRequest.setHeader(header.getName(), header.getValue());
    }
    chain.processNextPolicy(httpRequest);
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) HttpHeader(com.azure.android.core.http.HttpHeader)

Example 24 with HttpRequest

use of com.azure.android.core.http.HttpRequest in project azure-sdk-for-android by Azure.

the class AzureKeyCredentialPolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    if ("http".equals(chain.getRequest().getUrl().getProtocol())) {
        chain.completedError(new IllegalStateException("Key credentials require HTTPS to prevent leaking the key."));
    } else {
        HttpRequest httpRequest = chain.getRequest();
        httpRequest.setHeader(name, credential.getKey());
        chain.processNextPolicy(httpRequest);
    }
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest)

Example 25 with HttpRequest

use of com.azure.android.core.http.HttpRequest in project azure-sdk-for-android by Azure.

the class CookiePolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    HttpRequest httpRequest = chain.getRequest();
    final URI uri;
    try {
        uri = httpRequest.getUrl().toURI();
    } catch (URISyntaxException error) {
        chain.completedError(error);
        return;
    }
    Map<String, List<String>> cookieHeaders = new HashMap<>();
    for (HttpHeader header : httpRequest.getHeaders()) {
        cookieHeaders.put(header.getName(), Arrays.asList(chain.getRequest().getHeaders().getValues(header.getName())));
    }
    final Map<String, List<String>> requestCookies;
    try {
        requestCookies = cookies.get(uri, cookieHeaders);
    } catch (IOException error) {
        chain.completedError(error);
        return;
    }
    for (Map.Entry<String, List<String>> entry : requestCookies.entrySet()) {
        httpRequest.getHeaders().put(entry.getKey(), TextUtils.join(",", entry.getValue()));
    }
    chain.processNextPolicy(httpRequest, new NextPolicyCallback() {

        @Override
        public PolicyCompleter.CompletionState onSuccess(HttpResponse response, PolicyCompleter completer) {
            Map<String, List<String>> responseHeaders = new HashMap<>();
            for (HttpHeader header : response.getHeaders()) {
                responseHeaders.put(header.getName(), Collections.singletonList(header.getValue()));
            }
            try {
                cookies.put(uri, responseHeaders);
            } catch (IOException error) {
                return completer.completedError(error);
            }
            return completer.completed(response);
        }

        @Override
        public PolicyCompleter.CompletionState onError(Throwable error, PolicyCompleter completer) {
            return completer.completedError(error);
        }
    });
}
Also used : HttpRequest(com.azure.android.core.http.HttpRequest) HashMap(java.util.HashMap) HttpResponse(com.azure.android.core.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) HttpHeader(com.azure.android.core.http.HttpHeader) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) NextPolicyCallback(com.azure.android.core.http.NextPolicyCallback) PolicyCompleter(com.azure.android.core.http.PolicyCompleter)

Aggregations

HttpRequest (com.azure.android.core.http.HttpRequest)37 HttpResponse (com.azure.android.core.http.HttpResponse)22 HttpCallback (com.azure.android.core.http.HttpCallback)18 CountDownLatch (java.util.concurrent.CountDownLatch)18 HttpPipeline (com.azure.android.core.http.HttpPipeline)17 HttpPipelineBuilder (com.azure.android.core.http.HttpPipelineBuilder)17 CancellationToken (com.azure.android.core.util.CancellationToken)15 Test (org.junit.jupiter.api.Test)13 HttpHeaders (com.azure.android.core.http.HttpHeaders)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)5 HttpClient (com.azure.android.core.http.HttpClient)4 UrlBuilder (com.azure.android.core.http.util.UrlBuilder)4 IOException (java.io.IOException)4 HttpHeader (com.azure.android.core.http.HttpHeader)3 ClientLogger (com.azure.android.core.logging.ClientLogger)3 JacksonSerder (com.azure.android.core.serde.jackson.JacksonSerder)3 List (java.util.List)3 ResourceLock (org.junit.jupiter.api.parallel.ResourceLock)3 MethodSource (org.junit.jupiter.params.provider.MethodSource)3 LIBRARY_PACKAGE_NAME (com.azure.android.communication.chat.BuildConfig.LIBRARY_PACKAGE_NAME)2