Search in sources :

Example 31 with HttpResponse

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

the class RecordNetworkCallPolicy method process.

@Override
public void process(HttpPipelinePolicyChain chain) {
    final NetworkCallRecord networkCallRecord = new NetworkCallRecord();
    Map<String, String> headers = new HashMap<>();
    captureRequestHeaders(chain.getRequest().getHeaders(), headers, X_MS_CLIENT_REQUEST_ID, CONTENT_TYPE, X_MS_VERSION, USER_AGENT);
    networkCallRecord.setHeaders(headers);
    networkCallRecord.setMethod(chain.getRequest().getHttpMethod().toString());
    // Remove sensitive information such as SAS token signatures from the recording.
    UrlBuilder urlBuilder = UrlBuilder.parse(chain.getRequest().getUrl());
    redactedAccountName(urlBuilder);
    if (urlBuilder.getQuery().containsKey(SIG)) {
        urlBuilder.setQueryParameter(SIG, "REDACTED");
    }
    networkCallRecord.setUri(urlBuilder.toString().replaceAll("\\?$", ""));
    chain.processNextPolicy(chain.getRequest(), new NextPolicyCallback() {

        @Override
        public PolicyCompleter.CompletionState onSuccess(HttpResponse response, PolicyCompleter completer) {
            final HttpResponse bufferedResponse = response.buffer();
            Map<String, String> responseData = extractResponseData(bufferedResponse);
            networkCallRecord.setResponse(responseData);
            String body = responseData.get(BODY);
            // Remove pre-added header if this is a waiting or redirection
            if (body != null && body.contains("<Status>InProgress</Status>") || Integer.parseInt(responseData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) {
                logger.info("Waiting for a response or redirection.");
            } else {
                recordedData.addNetworkCall(networkCallRecord);
            }
            return completer.completed(bufferedResponse);
        }

        @Override
        public PolicyCompleter.CompletionState onError(Throwable error, PolicyCompleter completer) {
            networkCallRecord.setException(new NetworkCallError(error));
            recordedData.addNetworkCall(networkCallRecord);
            return completer.completedError(error);
        }
    });
}
Also used : HashMap(java.util.HashMap) HttpResponse(com.azure.android.core.http.HttpResponse) NetworkCallRecord(com.azure.android.core.test.models.NetworkCallRecord) UrlBuilder(com.azure.android.core.http.util.UrlBuilder) NextPolicyCallback(com.azure.android.core.http.NextPolicyCallback) HashMap(java.util.HashMap) Map(java.util.Map) PolicyCompleter(com.azure.android.core.http.PolicyCompleter) NetworkCallError(com.azure.android.core.test.models.NetworkCallError)

Example 32 with HttpResponse

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

the class HttpUrlConnectionAsyncHttpClient method sendIntern.

private void sendIntern(HttpRequest httpRequest, CancellationToken cancellationToken, HttpCallback httpCallback) {
    if (cancellationToken.isCancellationRequested()) {
        httpCallback.onError(new IOException("Canceled."));
        return;
    }
    final HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) httpRequest.getUrl().openConnection();
    } catch (IOException ioe) {
        httpCallback.onError(ioe);
        return;
    }
    connection.setDoInput(true);
    Throwable error = null;
    HttpResponse httpResponse = null;
    boolean hasResponseContent = false;
    try {
        // Request: headers
        for (HttpHeader header : httpRequest.getHeaders()) {
            connection.addRequestProperty(header.getName(), header.getValue());
        }
        // Request: method and content.
        switch(httpRequest.getHttpMethod()) {
            case GET:
            case HEAD:
            case OPTIONS:
            case TRACE:
                connection.setRequestMethod(httpRequest.getHttpMethod().toString());
                break;
            case PUT:
            case POST:
            case PATCH:
            case DELETE:
                connection.setRequestMethod(httpRequest.getHttpMethod().toString());
                final byte[] requestContent = httpRequest.getBody();
                if (requestContent != null) {
                    connection.setDoOutput(true);
                    final OutputStream requestContentStream = connection.getOutputStream();
                    try {
                        requestContentStream.write(requestContent);
                    } finally {
                        requestContentStream.close();
                    }
                }
                break;
            default:
                throw logger.logExceptionAsError(new IllegalStateException("Unknown HTTP Method:" + httpRequest.getHttpMethod()));
        }
        // Response: StatusCode
        final int statusCode = connection.getResponseCode();
        if (statusCode == -1) {
            final IOException ioException = new IOException("Retrieval of HTTP response code failed. " + "HttpUrlConnection::getResponseCode() returned -1");
            throw logger.logExceptionAsError(new RuntimeException(ioException));
        }
        // Response: headers
        final Map<String, List<String>> connHeaderMap = connection.getHeaderFields();
        final HttpHeaders headers = new HttpHeaders();
        for (Map.Entry<String, List<String>> entry : connHeaderMap.entrySet()) {
            if (entry.getKey() == null) {
                continue;
            }
            final String headerName = entry.getKey();
            final String headerValue;
            Iterator<String> hdrValueItr = entry.getValue().iterator();
            if (hdrValueItr.hasNext()) {
                headerValue = hdrValueItr.next();
            } else {
                headerValue = null;
            }
            headers.put(headerName, headerValue);
        }
        // Response: Content
        hasResponseContent = statusCode != HttpURLConnection.HTTP_NO_CONTENT && statusCode != HttpURLConnection.HTTP_NOT_MODIFIED && statusCode >= HttpURLConnection.HTTP_OK && httpRequest.getHttpMethod() != HttpMethod.HEAD;
        final InputStream responseContentStream = hasResponseContent ? new ResponseContentStream(connection) : new ByteArrayInputStream(new byte[0]);
        httpResponse = new UrlConnectionResponse(logger, httpRequest, statusCode, headers, responseContentStream);
    } catch (Throwable e) {
        error = e;
    } finally {
        if (error != null || !hasResponseContent) {
            connection.disconnect();
        }
    }
    if (error != null) {
        httpCallback.onError(error);
        return;
    } else {
        httpCallback.onSuccess(httpResponse);
    }
}
Also used : HttpHeaders(com.azure.android.core.http.HttpHeaders) FilterInputStream(java.io.FilterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) HttpResponse(com.azure.android.core.http.HttpResponse) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) HttpHeader(com.azure.android.core.http.HttpHeader) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Map(java.util.Map)

Aggregations

HttpResponse (com.azure.android.core.http.HttpResponse)32 HttpCallback (com.azure.android.core.http.HttpCallback)21 CountDownLatch (java.util.concurrent.CountDownLatch)21 HttpRequest (com.azure.android.core.http.HttpRequest)20 HttpPipeline (com.azure.android.core.http.HttpPipeline)18 Test (org.junit.jupiter.api.Test)18 HttpPipelineBuilder (com.azure.android.core.http.HttpPipelineBuilder)14 CancellationToken (com.azure.android.core.util.CancellationToken)13 HttpHeaders (com.azure.android.core.http.HttpHeaders)10 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 IOException (java.io.IOException)5 NextPolicyCallback (com.azure.android.core.http.NextPolicyCallback)4 PolicyCompleter (com.azure.android.core.http.PolicyCompleter)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 HttpHeader (com.azure.android.core.http.HttpHeader)3 HttpMethod (com.azure.android.core.http.HttpMethod)3 PagedResponse (com.azure.android.core.rest.util.paging.PagedResponse)3 JacksonSerder (com.azure.android.core.serde.jackson.JacksonSerder)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3