Search in sources :

Example 1 with HttpHeader

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

the class HttpRequestMapperTests method headerSubstitution.

@ParameterizedTest
@MethodSource("headerSubstitutionSupplier")
public void headerSubstitution(Method method, Object[] arguments, Map<String, String> expectedHeaders) {
    HttpRequestMapper mapper = new HttpRequestMapper("https://raw.host.com", method, new JacksonSerder());
    HttpHeaders actual = new HttpHeaders();
    mapper.applyHeaderMappings(arguments, actual);
    for (HttpHeader header : actual) {
        assertEquals(expectedHeaders.get(header.getName()), header.getValue());
    }
}
Also used : HttpHeaders(com.azure.android.core.http.HttpHeaders) JacksonSerder(com.azure.android.core.serde.jackson.JacksonSerder) HttpHeader(com.azure.android.core.http.HttpHeader) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 2 with HttpHeader

use of com.azure.android.core.http.HttpHeader 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 3 with HttpHeader

use of com.azure.android.core.http.HttpHeader 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 4 with HttpHeader

use of com.azure.android.core.http.HttpHeader 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)

Example 5 with HttpHeader

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

the class HttpLoggingPolicy method appendHeaders.

/*
     * Adds HTTP headers into the StringBuilder that is generating the log message.
     *
     * @param headers HTTP headers on the request or response.
     * @param sb StringBuilder that is generating the log message.
     * @param logLevel Log level the environment is configured to use.
     */
private void appendHeaders(ClientLogger logger, HttpHeaders headers, StringBuilder logMessage) {
    // Either headers shouldn't be logged or the logging level isn't set to VERBOSE, don't add headers.
    if (!httpLogDetailLevel.shouldLogHeaders() || !logger.canLogAtLevel(LogLevel.VERBOSE)) {
        return;
    }
    for (HttpHeader header : headers) {
        String headerName = header.getName();
        logMessage.append(headerName).append(":");
        if (allowedHeaderNames.contains(headerName.toLowerCase(Locale.ROOT))) {
            logMessage.append(header.getValue());
        } else {
            logMessage.append(REDACTED_PLACEHOLDER);
        }
        logMessage.append(LINE_SEPARATOR);
    }
}
Also used : HttpHeader(com.azure.android.core.http.HttpHeader)

Aggregations

HttpHeader (com.azure.android.core.http.HttpHeader)9 HttpHeaders (com.azure.android.core.http.HttpHeaders)4 IOException (java.io.IOException)4 HttpRequest (com.azure.android.core.http.HttpRequest)3 HttpResponse (com.azure.android.core.http.HttpResponse)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 JacksonSerder (com.azure.android.core.serde.jackson.JacksonSerder)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 List (java.util.List)2 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 MethodSource (org.junit.jupiter.params.provider.MethodSource)2 NextPolicyCallback (com.azure.android.core.http.NextPolicyCallback)1 PolicyCompleter (com.azure.android.core.http.PolicyCompleter)1 RecordingRedactor (com.azure.android.core.test.models.RecordingRedactor)1 FilterInputStream (java.io.FilterInputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 HttpURLConnection (java.net.HttpURLConnection)1