Search in sources :

Example 51 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project java-sdk by smartcar.

the class Vehicle method lock.

/**
 * Send request to the /security endpoint to lock a vehicle
 *
 * @return a response indicating success
 * @throws SmartcarException if the request is unsuccessful
 */
public ActionResponse lock() throws SmartcarException {
    JsonObject json = Json.createObjectBuilder().add("action", "LOCK").build();
    RequestBody body = RequestBody.create(ApiClient.JSON, json.toString());
    return this.call("security", "POST", body, ActionResponse.class);
}
Also used : JsonObject(javax.json.JsonObject) RequestBody(okhttp3.RequestBody)

Example 52 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project spring-cloud-square by spring-projects-experimental.

the class WebClientCallAdapterFactory method requestBuilder.

WebClient.RequestBodySpec requestBuilder(WebClient webClient, Request request) {
    WebClient.RequestBodySpec spec = webClient.mutate().build().method(HttpMethod.resolve(request.method())).uri(request.url().uri()).headers(httpHeaders -> {
        for (Map.Entry<String, List<String>> entry : request.headers().toMultimap().entrySet()) {
            httpHeaders.put(entry.getKey(), entry.getValue());
        }
    });
    RequestBody requestBody = request.body();
    if (requestBody != null) {
        processRequestBody(spec, requestBody);
    }
    return spec;
}
Also used : List(java.util.List) WebClient(org.springframework.web.reactive.function.client.WebClient) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 53 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project spring-cloud-square by spring-projects-experimental.

the class SpringRequestConverter method convert.

@Override
public RequestBody convert(T value) throws IOException {
    if (value != null) {
        if (log.isDebugEnabled()) {
            if (this.contentType != null) {
                log.debug("Writing [" + value + "] as \"" + this.contentType + "\" using [" + messageConverter + "]");
            } else {
                log.debug("Writing [" + value + "] using [" + messageConverter + "]");
            }
        }
        return new RequestBody() {

            @Override
            public okhttp3.MediaType contentType() {
                return okhttp3.MediaType.parse(SpringRequestConverter.this.contentType.toString());
            }

            @Override
            public void writeTo(BufferedSink bufferedSink) throws IOException {
                @SuppressWarnings("unchecked") HttpMessageConverter<Object> copy = (HttpMessageConverter<Object>) messageConverter;
                copy.write(value, SpringRequestConverter.this.contentType, new HttpOutputMessage() {

                    @Override
                    public OutputStream getBody() throws IOException {
                        return bufferedSink.outputStream();
                    }

                    @Override
                    public HttpHeaders getHeaders() {
                        // TODO: where to get headers?
                        return new HttpHeaders();
                    }
                });
            }
        };
    /*
			 * FeignOutputMessage outputMessage = new FeignOutputMessage(request); try {
			 *
			 * @SuppressWarnings("unchecked") HttpMessageConverter<Object> copy =
			 * (HttpMessageConverter<Object>) messageConverter; copy.write(requestBody,
			 * this.contentType, outputMessage); } catch (IOException ex) { throw new
			 * EncodeException("Error converting request body", ex); } // clear headers
			 * request.headers(null); // converters can modify headers, so update the
			 * request // with the modified headers
			 * request.headers(getHeaders(outputMessage.getHeaders()));
			 * request.body(outputMessage.getOutputStream().toByteArray(),
			 * Charset.forName("UTF-8")); // TODO: set charset return;
			 */
    }
    return null;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpOutputMessage(org.springframework.http.HttpOutputMessage) OutputStream(java.io.OutputStream) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 54 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project neow3j by neow3j.

the class HttpService method performIO.

@Override
protected InputStream performIO(String request) throws IOException {
    RequestBody requestBody = RequestBody.create(JSON_MEDIA_TYPE, request);
    Headers headers = buildHeaders();
    okhttp3.Request httpRequest = new okhttp3.Request.Builder().url(url).headers(headers).post(requestBody).build();
    okhttp3.Response response = httpClient.newCall(httpRequest).execute();
    ResponseBody responseBody = response.body();
    if (response.isSuccessful()) {
        if (responseBody != null) {
            return buildInputStream(responseBody);
        } else {
            return null;
        }
    } else {
        int code = response.code();
        String text = responseBody == null ? "N/A" : responseBody.string();
        throw new ClientConnectionException("Invalid response received: " + code + "; " + text);
    }
}
Also used : ClientConnectionException(io.neow3j.protocol.exceptions.ClientConnectionException) Headers(okhttp3.Headers) RequestBody(okhttp3.RequestBody) ResponseBody(okhttp3.ResponseBody)

Example 55 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project nightfall-java-sdk by nightfallai.

the class NightfallClient method issueRequest.

/**
 * Issues an HTTP request to the provided resource. If the request is successful, the response body will be
 * deserialized into an object based on the provided <code>responseClass</code>. If the response indicates a
 * rate limiting error, the request will be retried after a short sleep.
 *
 * @param path the HTTP resource path
 * @param method the HTTP verb
 * @param body the HTTP request body
 * @param headers HTTP headers
 * @param responseClass the class to deserialize results into
 * @return an instance of the <code>responseClass</code>
 * @throws NightfallClientException thrown if an unexpected error occurs while processing the request
 * @throws NightfallAPIException thrown if the API returns a 4xx or 5xx error code
 * @throws NightfallRequestTimeoutException thrown if the request is aborted because read/write timeout is exceeded
 */
private <E> E issueRequest(String path, String method, MediaType mediaType, byte[] body, Headers headers, Class<E> responseClass) {
    String url = this.apiHost + path;
    Request.Builder builder = new Request.Builder().url(url);
    if (headers != null) {
        builder.headers(headers);
    }
    if (this.implVersion != null && !this.implVersion.equals("")) {
        builder.addHeader("User-Agent", "nightfall-java-sdk/" + this.implVersion);
    }
    builder.addHeader("Authorization", "Bearer " + this.apiKey);
    RequestBody reqBody = null;
    if (body != null && body.length > 0) {
        reqBody = RequestBody.create(body, mediaType);
    } else if (!method.equals("GET") && !method.equals("HEAD")) {
        reqBody = RequestBody.create(new byte[0]);
    }
    builder.method(method, reqBody);
    Request request = builder.build();
    Call call = this.httpClient.newCall(request);
    NightfallErrorResponse lastError = null;
    int errorCode = 0;
    for (int attempt = 0; attempt < this.retryCount; attempt++) {
        try (Response response = call.execute()) {
            if (!response.isSuccessful()) {
                try {
                    lastError = objectMapper.readValue(response.body().bytes(), NightfallErrorResponse.class);
                } catch (Throwable t) {
                // best effort to get more info, swallow failure
                }
                if (response.code() == 429 && attempt < this.retryCount - 1) {
                    Thread.sleep(1000);
                    // cannot re-use the same call object
                    call = call.clone();
                    continue;
                }
                // cannot directly throw exception here because of Throwable catch branch; need to break
                errorCode = response.code();
                break;
            }
            if (Void.class.equals(responseClass)) {
                return null;
            }
            return objectMapper.readValue(response.body().bytes(), responseClass);
        } catch (IOException e) {
            // If OkHTTP times out, allow retries
            if (e.getMessage().equalsIgnoreCase("timeout") || e.getMessage().equalsIgnoreCase("read timed out")) {
                if (attempt >= this.retryCount - 1) {
                    throw new NightfallRequestTimeoutException("request timed out");
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ee) {
                // swallow
                }
                // cannot re-use the same call object
                call = call.clone();
                continue;
            }
            throw new NightfallClientException("issuing HTTP request: " + e.getMessage());
        } catch (Throwable t) {
            throw new NightfallClientException("failure executing HTTP request: " + t.getMessage());
        }
    }
    if (errorCode > 0) {
        throw new NightfallAPIException("unsuccessful response", lastError, errorCode);
    }
    String message = "exceeded max retry count on request: " + path;
    throw new NightfallAPIException(message, lastError, 429);
}
Also used : Call(okhttp3.Call) NightfallClientException(ai.nightfall.scan.model.NightfallClientException) NightfallRequestTimeoutException(ai.nightfall.scan.model.NightfallRequestTimeoutException) InitializeFileUploadRequest(ai.nightfall.scan.model.InitializeFileUploadRequest) ScanFileRequest(ai.nightfall.scan.model.ScanFileRequest) Request(okhttp3.Request) ScanTextRequest(ai.nightfall.scan.model.ScanTextRequest) UploadFileChunkRequest(ai.nightfall.scan.model.UploadFileChunkRequest) CompleteFileUploadRequest(ai.nightfall.scan.model.CompleteFileUploadRequest) IOException(java.io.IOException) NightfallAPIException(ai.nightfall.scan.model.NightfallAPIException) ScanTextResponse(ai.nightfall.scan.model.ScanTextResponse) NightfallErrorResponse(ai.nightfall.scan.model.NightfallErrorResponse) Response(okhttp3.Response) ScanFileResponse(ai.nightfall.scan.model.ScanFileResponse) NightfallErrorResponse(ai.nightfall.scan.model.NightfallErrorResponse) RequestBody(okhttp3.RequestBody)

Aggregations

RequestBody (okhttp3.RequestBody)1358 Request (okhttp3.Request)785 Response (okhttp3.Response)598 IOException (java.io.IOException)420 Test (org.junit.Test)235 OkHttpClient (okhttp3.OkHttpClient)216 MultipartBody (okhttp3.MultipartBody)213 MediaType (okhttp3.MediaType)204 Call (okhttp3.Call)198 JSONObject (org.json.JSONObject)183 ResponseBody (okhttp3.ResponseBody)177 Callback (okhttp3.Callback)115 FormBody (okhttp3.FormBody)106 Buffer (okio.Buffer)98 File (java.io.File)92 Map (java.util.Map)90 JsonObject (io.vertx.core.json.JsonObject)89 Headers (okhttp3.Headers)88 HashMap (java.util.HashMap)83 HttpUrl (okhttp3.HttpUrl)80