Search in sources :

Example 46 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project android-library by nextcloud.

the class SetUserInfoRemoteOperation method run.

@Override
public RemoteOperationResult<Boolean> run(NextcloudClient client) {
    RemoteOperationResult<Boolean> result;
    PutMethod method = null;
    try {
        // request body
        MediaType json = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(json, "{\"key\": \"" + field.getFieldName() + "\"" + ", \"value\": \"" + value + "\"}");
        // remote request
        method = new PutMethod(client.getBaseUri() + OCS_ROUTE_PATH + client.getUserId(), true, requestBody);
        int status = client.execute(method);
        if (status == HttpStatus.SC_OK) {
            result = new RemoteOperationResult<>(true, method);
        } else {
            result = new RemoteOperationResult<>(false, method);
            String response = method.getResponseBodyAsString();
            Log_OC.e(TAG, "Failed response while setting user information");
            Log_OC.e(TAG, "*** status code: " + status + "; response: " + response);
        }
    } catch (Exception e) {
        result = new RemoteOperationResult<>(e);
        Log_OC.e(TAG, "Exception while setting OC user information", e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return result;
}
Also used : RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) PutMethod(com.nextcloud.operations.PutMethod) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 47 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project cordova-plugin-background-upload by spoonconsulting.

the class UploadTask method createRequest.

/**
 * Create the OkHttp request that will be used, already filled with input data.
 *
 * @return A ready to use OkHttp request
 * @throws FileNotFoundException If the file to upload can't be found
 */
@NonNull
private Request createRequest() throws FileNotFoundException {
    final String filepath = getInputData().getString(KEY_INPUT_FILEPATH);
    assert filepath != null;
    final String fileKey = getInputData().getString(KEY_INPUT_FILE_KEY);
    assert fileKey != null;
    // Build URL
    HttpUrl url = Objects.requireNonNull(HttpUrl.parse(getInputData().getString(KEY_INPUT_URL))).newBuilder().build();
    // Build file reader
    String extension = MimeTypeMap.getFileExtensionFromUrl(filepath);
    MediaType mediaType = MediaType.parse(MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
    File file = new File(filepath);
    ProgressRequestBody fileRequestBody = new ProgressRequestBody(mediaType, file.length(), new FileInputStream(file), this::handleProgress);
    // Build body
    final MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
    // With the parameters
    final int parametersCount = getInputData().getInt(KEY_INPUT_PARAMETERS_COUNT, 0);
    if (parametersCount > 0) {
        final String[] parameterNames = getInputData().getStringArray(KEY_INPUT_PARAMETERS_NAMES);
        assert parameterNames != null;
        for (int i = 0; i < parametersCount; i++) {
            final String key = parameterNames[i];
            final Object value = getInputData().getKeyValueMap().get(KEY_INPUT_PARAMETER_VALUE_PREFIX + i);
            bodyBuilder.addFormDataPart(key, value.toString());
        }
    }
    bodyBuilder.addFormDataPart(fileKey, filepath, fileRequestBody);
    // Start build request
    String method = getInputData().getString(KEY_INPUT_HTTP_METHOD);
    if (method == null) {
        method = "POST";
    }
    Request.Builder requestBuilder = new Request.Builder().url(url).method(method.toUpperCase(), bodyBuilder.build());
    // Write headers
    final int headersCount = getInputData().getInt(KEY_INPUT_HEADERS_COUNT, 0);
    final String[] headerNames = getInputData().getStringArray(KEY_INPUT_HEADERS_NAMES);
    assert headerNames != null;
    for (int i = 0; i < headersCount; i++) {
        final String key = headerNames[i];
        final Object value = getInputData().getKeyValueMap().get(KEY_INPUT_HEADER_VALUE_PREFIX + i);
        requestBuilder.addHeader(key, value.toString());
    }
    // Ok
    return requestBuilder.build();
}
Also used : Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) FileInputStream(java.io.FileInputStream) MultipartBody(okhttp3.MultipartBody) MediaType(okhttp3.MediaType) File(java.io.File) NonNull(androidx.annotation.NonNull)

Example 48 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project OkHttpRestAssuredExamples by mfaisalkhatri.

the class TestPatchRequests method testPatchWithOkHttp.

/**
 * Executing Put Request using OkHttp
 *
 * @since Mar 8, 2020
 * @param id
 * @param name
 * @param job
 * @throws IOException
 */
@Test(dataProvider = "patchData", groups = "PatchTests")
public void testPatchWithOkHttp(final int id, final String name, final String job) throws IOException {
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    final PostData postData = new PostData(name, job);
    final OkHttpClient client = new OkHttpClient();
    final JSONObject json = new JSONObject(postData);
    final RequestBody requestBody = RequestBody.create(json.toString(), JSON);
    final Request request = new Request.Builder().url(URL + "/api/users" + id).addHeader("Content-Type", "application/json;charset=utf-8").patch(requestBody).build();
    final Response response = client.newCall(request).execute();
    final int statusCode = response.code();
    this.log.info(statusCode);
    final String responseBody = response.body().string();
    this.log.info(responseBody);
    final JSONObject jsonResponse = new JSONObject(responseBody);
    assertEquals(statusCode, 200);
    assertThat(jsonResponse.getString("name"), equalTo(name));
    assertThat(jsonResponse.getString("job"), equalTo(job));
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) Test(org.testng.annotations.Test)

Example 49 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project OkHttpRestAssuredExamples by mfaisalkhatri.

the class TestPostRequest method testPostWithOkHttp.

/**
 * @since Mar 7, 2020
 * @param name
 * @param job
 * @throws IOException
 */
@Test(dataProvider = "postData", groups = "PostTests")
public void testPostWithOkHttp(final String name, final String job) throws IOException {
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    final PostData postData = new PostData(name, job);
    final OkHttpClient client = new OkHttpClient();
    final JSONObject json = new JSONObject(postData);
    final RequestBody requestBody = RequestBody.create(json.toString(), JSON);
    final Request request = new Request.Builder().url(URL + "/api/users").addHeader("Content-Type", "application/json;charset=utf-8").post(requestBody).build();
    final Response response = client.newCall(request).execute();
    final int statusCode = response.code();
    this.log.info(statusCode);
    final String responseBody = response.body().string();
    this.log.info(responseBody);
    final JSONObject jsonResponse = new JSONObject(responseBody);
    assertEquals(statusCode, 201);
    assertThat(jsonResponse.getString("name"), equalTo(name));
    assertThat(jsonResponse.getString("job"), equalTo(job));
    assertThat(jsonResponse.getString("id"), notNullValue());
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) Test(org.testng.annotations.Test)

Example 50 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project OkHttpRestAssuredExamples by mfaisalkhatri.

the class TestPutRequests method testPutWithOkHttp.

/**
 * Executing Put Request using OkHttp
 *
 * @since Mar 8, 2020
 * @param id
 * @param name
 * @param job
 * @throws IOException
 */
@Test(dataProvider = "putData", groups = "PutTests")
public void testPutWithOkHttp(final int id, final String name, final String job) throws IOException {
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    final PostData postData = new PostData(name, job);
    final OkHttpClient client = new OkHttpClient();
    final JSONObject json = new JSONObject(postData);
    final RequestBody requestBody = RequestBody.create(json.toString(), JSON);
    final Request request = new Request.Builder().url(URL + "/api/users" + id).addHeader("Content-Type", "application/json;charset=utf-8").put(requestBody).build();
    final Response response = client.newCall(request).execute();
    final int statusCode = response.code();
    this.log.info(statusCode);
    final String responseBody = response.body().string();
    this.log.info(responseBody);
    final JSONObject jsonResponse = new JSONObject(responseBody);
    assertEquals(statusCode, 200);
    assertThat(jsonResponse.getString("name"), equalTo(name));
    assertThat(jsonResponse.getString("job"), equalTo(job));
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) Test(org.testng.annotations.Test)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21