Search in sources :

Example 56 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project okta-commons-java by okta.

the class OkHttpRequestExecutor method executeRequest.

@Override
public Response executeRequest(Request request) throws HttpException {
    // Sign the request
    this.requestAuthenticator.authenticate(request);
    HttpUrl.Builder urlBuilder = HttpUrl.get(request.getResourceUrl()).newBuilder();
    // query params
    request.getQueryString().forEach(urlBuilder::addQueryParameter);
    okhttp3.Request.Builder okRequestBuilder = new okhttp3.Request.Builder().url(urlBuilder.build());
    // headers
    request.getHeaders().toSingleValueMap().forEach(okRequestBuilder::addHeader);
    boolean isMultipartFormDataForFileUploading = false;
    String xContentType = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-contentType");
    if (!Strings.isEmpty(xContentType)) {
        isMultipartFormDataForFileUploading = xContentType.equals(MediaType.MULTIPART_FORM_DATA_VALUE);
    }
    HttpMethod method = request.getMethod();
    switch(method) {
        case DELETE:
            okRequestBuilder.delete();
            break;
        case GET:
            okRequestBuilder.get();
            break;
        case HEAD:
            okRequestBuilder.head();
            break;
        case POST:
            if (isMultipartFormDataForFileUploading) {
                String fileLocation = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-fileLocation");
                String formDataPartName = RequestUtils.fetchHeaderValueAndRemoveIfPresent(request, "x-fileFormDataName");
                File file = new File(fileLocation);
                RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart(formDataPartName, file.getName(), RequestBody.create(null, file)).build();
                okRequestBuilder.post(requestBody);
            } else {
                okRequestBuilder.post(new InputStreamRequestBody(request.getBody(), request.getHeaders().getContentType()));
            }
            break;
        case PUT:
            // TODO support 100-continue ?
            okRequestBuilder.put(new InputStreamRequestBody(request.getBody(), request.getHeaders().getContentType()));
            break;
        default:
            throw new IllegalArgumentException("Unrecognized HttpMethod: " + method);
    }
    try {
        okhttp3.Response okResponse = client.newCall(okRequestBuilder.build()).execute();
        return toSdkResponse(okResponse);
    } catch (SocketException | SocketTimeoutException e) {
        throw new HttpException("Unable to execute HTTP request - retryable exception: " + e.getMessage(), e, true);
    } catch (IOException e) {
        throw new HttpException(e.getMessage(), e);
    }
}
Also used : SocketException(java.net.SocketException) Request(com.okta.commons.http.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) SocketTimeoutException(java.net.SocketTimeoutException) MultipartBody(okhttp3.MultipartBody) HttpException(com.okta.commons.http.HttpException) File(java.io.File) HttpMethod(com.okta.commons.http.HttpMethod) RequestBody(okhttp3.RequestBody)

Example 57 with RequestBody

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

the class SeafConnection method uploadFileCommon.

/**
 * Upload a file to seafile httpserver
 */
private String uploadFileCommon(String link, String repoID, String dir, String filePath, ProgressMonitor monitor, boolean update) throws SeafException, IOException {
    File file = new File(filePath);
    if (!file.exists()) {
        throw new SeafException(SeafException.OTHER_EXCEPTION, "File not exists");
    }
    MultipartBody.Builder builder = new MultipartBody.Builder();
    // set type
    builder.setType(MultipartBody.FORM);
    // "target_file" "parent_dir"  must be "/" end off
    if (update) {
        String targetFilePath = Utils.pathJoin(dir, file.getName());
        builder.addFormDataPart("target_file", targetFilePath);
    } else {
        builder.addFormDataPart("parent_dir", dir);
    }
    builder.addFormDataPart("file", file.getName(), RequestManager.getInstance(account).createProgressRequestBody(monitor, file));
    // create RequestBody
    RequestBody body = builder.build();
    // create Request
    final Request request = new Request.Builder().url(link).post(body).header("Authorization", "Token " + account.token).build();
    Response response = RequestManager.getInstance(account).getClient().newCall(request).execute();
    if (response.isSuccessful()) {
        String str = response.body().string();
        if (!TextUtils.isEmpty(str)) {
            return str.replace("\"", "");
        }
    }
    throw new SeafException(SeafException.OTHER_EXCEPTION, "File upload failed");
}
Also used : Response(okhttp3.Response) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) HttpRequest(com.github.kevinsawicki.http.HttpRequest) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 58 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project springframework-source-5.1.x by wb02125055.

the class OkHttp3ClientHttpRequestFactory method buildRequest.

static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method) throws MalformedURLException {
    okhttp3.MediaType contentType = getContentType(headers);
    RequestBody body = (content.length > 0 || okhttp3.internal.http.HttpMethod.requiresRequestBody(method.name()) ? RequestBody.create(contentType, content) : null);
    Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body);
    headers.forEach((headerName, headerValues) -> {
        for (String headerValue : headerValues) {
            builder.addHeader(headerName, headerValue);
        }
    });
    return builder.build();
}
Also used : Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 59 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project odysee-android by OdyseeTeam.

the class Comments method performRequest.

/**
 * Performs the request to Comment Server
 * @param commentServer Url where to direct the request
 * @param params JSON containing parameters to send to the server
 * @param method One of the available methods for comments
 * @return Response from the server
 * @throws IOException throwable from OkHttpClient execute()
 */
public static Response performRequest(String commentServer, JSONObject params, String method) throws IOException {
    final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    Map<String, Object> requestParams = new HashMap<>(4);
    requestParams.put("jsonrpc", "2.0");
    requestParams.put("id", 1);
    requestParams.put("method", method);
    requestParams.put("params", params);
    final String jsonString = Lbry.buildJsonParams(requestParams).toString();
    RequestBody requestBody = RequestBody.create(jsonString, JSON);
    Request commentCreateRequest = new Request.Builder().url(commentServer.concat("?m=").concat(method)).post(requestBody).build();
    OkHttpClient client = new OkHttpClient.Builder().writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();
    return client.newCall(commentCreateRequest).execute();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HashMap(java.util.HashMap) Request(okhttp3.Request) MediaType(okhttp3.MediaType) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Example 60 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project odysee-android by OdyseeTeam.

the class Lbry method apiCall.

public static Response apiCall(String method, Map<String, Object> params, String connectionString, String authToken) throws LbryRequestException {
    long counter = new Double(System.currentTimeMillis() / 1000.0).longValue();
    if (Helper.isNullOrEmpty(authToken) && params != null && params.containsKey("auth_token") && params.get("auth_token") != null) {
        authToken = params.get("auth_token").toString();
        params.remove("auth_token");
    }
    JSONObject requestParams = buildJsonParams(params);
    JSONObject requestBody = new JSONObject();
    try {
        requestBody.put("jsonrpc", "2.0");
        requestBody.put("method", method);
        requestBody.put("params", requestParams);
        requestBody.put("counter", counter);
    } catch (JSONException ex) {
        throw new LbryRequestException("Could not build the JSON request body.", ex);
    }
    RequestBody body = RequestBody.create(requestBody.toString(), Helper.JSON_MEDIA_TYPE);
    Request.Builder requestBuilder = new Request.Builder().url(connectionString).post(body);
    if (!Helper.isNullOrEmpty(authToken)) {
        requestBuilder.addHeader("X-Lbry-Auth-Token", authToken);
    }
    Request request = requestBuilder.build();
    OkHttpClient client = new OkHttpClient.Builder().writeTimeout(300, TimeUnit.SECONDS).readTimeout(300, TimeUnit.SECONDS).build();
    try {
        return client.newCall(request).execute();
    } catch (IOException ex) {
        throw new LbryRequestException(String.format("\"%s\" method to %s failed", method, connectionString), ex);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) JSONException(org.json.JSONException) IOException(java.io.IOException) LbryRequestException(com.odysee.app.exceptions.LbryRequestException) 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