Search in sources :

Example 81 with RequestBody

use of okhttp3.RequestBody in project graylog2-server by Graylog2.

the class HTTPAlarmCallbackTest method callSucceedsIfRemoteRequestSucceeds.

@Test
public void callSucceedsIfRemoteRequestSucceeds() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(200));
    server.start();
    final Configuration configuration = new Configuration(ImmutableMap.of("url", server.url("/").toString()));
    alarmCallback.initialize(configuration);
    alarmCallback.checkConfiguration();
    final Stream stream = new StreamMock(ImmutableMap.of("_id", "stream-id", "title", "Stream Title", "description", "Stream Description"), ImmutableList.of());
    final AlertCondition alertCondition = new DummyAlertCondition(stream, "condition-id", new DateTime(2016, 9, 6, 17, 0, DateTimeZone.UTC), "user", ImmutableMap.of(), "Alert Condition Title");
    final List<MessageSummary> messageSummaries = ImmutableList.of(new MessageSummary("graylog_1", new Message("Test message 1", "source1", new DateTime(2016, 9, 6, 17, 0, DateTimeZone.UTC))), new MessageSummary("graylog_2", new Message("Test message 2", "source2", new DateTime(2016, 9, 6, 17, 0, DateTimeZone.UTC))));
    final AlertCondition.CheckResult checkResult = new AbstractAlertCondition.CheckResult(true, alertCondition, "Result Description", new DateTime(2016, 9, 6, 17, 0, DateTimeZone.UTC), messageSummaries);
    alarmCallback.call(stream, checkResult);
    final RecordedRequest request = server.takeRequest();
    assertThat(request.getPath()).isEqualTo("/");
    assertThat(request.getHeader("Content-Type")).isEqualTo("application/json");
    assertThat(request.getBodySize()).isPositive();
    final String requestBody = request.getBody().readUtf8();
    final JsonNode jsonNode = objectMapper.readTree(requestBody);
    assertThat(jsonNode.get("check_result").get("matching_messages").size()).isEqualTo(2);
    assertThat(jsonNode.get("check_result").get("triggered").asBoolean()).isTrue();
    assertThat(jsonNode.get("check_result").get("triggered_at").asText()).isEqualTo("2016-09-06T17:00:00.000Z");
    assertThat(jsonNode.get("stream").get("id").asText()).isEqualTo("stream-id");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Configuration(org.graylog2.plugin.configuration.Configuration) Message(org.graylog2.plugin.Message) JsonNode(com.fasterxml.jackson.databind.JsonNode) DateTime(org.joda.time.DateTime) StreamMock(org.graylog2.streams.StreamMock) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) AbstractAlertCondition(org.graylog2.alerts.AbstractAlertCondition) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) MessageSummary(org.graylog2.plugin.MessageSummary) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) Test(org.junit.Test)

Example 82 with RequestBody

use of okhttp3.RequestBody in project AntennaPod by AntennaPod.

the class GpodnetService method uploadChanges.

/**
     * Updates the subscription list of a specific device.
     * <p/>
     * This method requires authentication.
     *
     * @param username The username. Must be the same user as the one which is
     *                 currently logged in.
     * @param deviceId The ID of the device whose subscriptions should be updated.
     * @param added    Collection of feed URLs of added feeds. This Collection MUST NOT contain any duplicates
     * @param removed  Collection of feed URLs of removed feeds. This Collection MUST NOT contain any duplicates
     * @return a GpodnetUploadChangesResponse. See {@link de.danoeh.antennapod.core.gpoddernet.model.GpodnetUploadChangesResponse}
     * for details.
     * @throws java.lang.IllegalArgumentException                           if username, deviceId, added or removed is null.
     * @throws de.danoeh.antennapod.core.gpoddernet.GpodnetServiceException if added or removed contain duplicates or if there
     *                                                                      is an authentication error.
     */
public GpodnetUploadChangesResponse uploadChanges(@NonNull String username, @NonNull String deviceId, @NonNull Collection<String> added, @NonNull Collection<String> removed) throws GpodnetServiceException {
    try {
        URL url = new URI(BASE_SCHEME, BASE_HOST, String.format("/api/2/subscriptions/%s/%s.json", username, deviceId), null).toURL();
        final JSONObject requestObject = new JSONObject();
        requestObject.put("add", new JSONArray(added));
        requestObject.put("remove", new JSONArray(removed));
        RequestBody body = RequestBody.create(JSON, requestObject.toString());
        Request.Builder request = new Request.Builder().post(body).url(url);
        final String response = executeRequest(request);
        return GpodnetUploadChangesResponse.fromJSONObject(response);
    } catch (JSONException | MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONArray(org.json.JSONArray) Request(okhttp3.Request) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Example 83 with RequestBody

use of okhttp3.RequestBody in project AntennaPod by AntennaPod.

the class GpodnetService method uploadEpisodeActions.

/**
     * Updates the episode actions
     * <p/>
     * This method requires authentication.
     *
     * @param episodeActions    Collection of episode actions.
     * @return a GpodnetUploadChangesResponse. See {@link de.danoeh.antennapod.core.gpoddernet.model.GpodnetUploadChangesResponse}
     * for details.
     * @throws java.lang.IllegalArgumentException                           if username, deviceId, added or removed is null.
     * @throws de.danoeh.antennapod.core.gpoddernet.GpodnetServiceException if added or removed contain duplicates or if there
     *                                                                      is an authentication error.
     */
public GpodnetEpisodeActionPostResponse uploadEpisodeActions(@NonNull Collection<GpodnetEpisodeAction> episodeActions) throws GpodnetServiceException {
    String username = GpodnetPreferences.getUsername();
    try {
        URL url = new URI(BASE_SCHEME, BASE_HOST, String.format("/api/2/episodes/%s.json", username), null).toURL();
        final JSONArray list = new JSONArray();
        for (GpodnetEpisodeAction episodeAction : episodeActions) {
            JSONObject obj = episodeAction.writeToJSONObject();
            if (obj != null) {
                list.put(obj);
            }
        }
        RequestBody body = RequestBody.create(JSON, list.toString());
        Request.Builder request = new Request.Builder().post(body).url(url);
        final String response = executeRequest(request);
        return GpodnetEpisodeActionPostResponse.fromJSONObject(response);
    } catch (JSONException | MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONArray(org.json.JSONArray) Request(okhttp3.Request) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) GpodnetEpisodeAction(de.danoeh.antennapod.core.gpoddernet.model.GpodnetEpisodeAction) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Example 84 with RequestBody

use of okhttp3.RequestBody in project AntennaPod by AntennaPod.

the class GpodnetService method uploadSubscriptions.

/**
     * Uploads the subscriptions of a specific device.
     * <p/>
     * This method requires authentication.
     *
     * @param username      The username. Must be the same user as the one which is
     *                      currently logged in.
     * @param deviceId      The ID of the device whose subscriptions should be updated.
     * @param subscriptions A list of feed URLs containing all subscriptions of the
     *                      device.
     * @throws IllegalArgumentException              If username, deviceId or subscriptions is null.
     * @throws GpodnetServiceAuthenticationException If there is an authentication error.
     */
public void uploadSubscriptions(@NonNull String username, @NonNull String deviceId, @NonNull List<String> subscriptions) throws GpodnetServiceException {
    try {
        URL url = new URI(BASE_SCHEME, BASE_HOST, String.format("/subscriptions/%s/%s.txt", username, deviceId), null).toURL();
        StringBuilder builder = new StringBuilder();
        for (String s : subscriptions) {
            builder.append(s);
            builder.append("\n");
        }
        RequestBody body = RequestBody.create(TEXT, builder.toString());
        Request.Builder request = new Request.Builder().put(body).url(url);
        executeRequest(request);
    } catch (MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Request(okhttp3.Request) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) RequestBody(okhttp3.RequestBody)

Example 85 with RequestBody

use of okhttp3.RequestBody in project amhttp by Eddieyuan123.

the class RequestManager method post.

public <T> void post(Context context, String url, CacheControl cacheControl, HashMap<String, String> headers, HashMap<String, String> params, Object tag, int callMethod, final OnAddListener<T> listener) {
    try {
        IRequestBodyFactory requestBodyFactory = new RequestBodyFactoryImpl();
        RequestBody requestBody = requestBodyFactory.buildRequestBody(params);
        final Request request = new Request.Builder().cacheControl(cacheControl == null ? CacheControl.FORCE_NETWORK : cacheControl).headers(Headers.of(headers)).tag(tag == null ? context.hashCode() : tag).url(url).post(requestBody).build();
        if (callMethod == CallMethod.SYNC) {
            RequestUtils.execute(mOkHttpClient, request, listener);
        } else {
            RequestUtils.enqueue(mOkHttpClient, request, listener);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Request(okhttp3.Request) ProgressRequestBody(io.chelizi.amokhttp.upload.ProgressRequestBody) RequestBody(okhttp3.RequestBody)

Aggregations

RequestBody (okhttp3.RequestBody)178 Request (okhttp3.Request)141 IOException (java.io.IOException)75 Response (okhttp3.Response)74 Test (org.junit.Test)53 ResponseBody (okhttp3.ResponseBody)32 Call (okhttp3.Call)31 MultipartBody (okhttp3.MultipartBody)28 MediaType (okhttp3.MediaType)27 FormBody (okhttp3.FormBody)25 Callback (okhttp3.Callback)23 Buffer (okio.Buffer)23 MockResponse (okhttp3.mockwebserver.MockResponse)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestClients.clientRequest (keywhiz.TestClients.clientRequest)15 BufferedSink (okio.BufferedSink)15 Headers (okhttp3.Headers)12 HttpUrl (okhttp3.HttpUrl)11 JSONObject (org.json.JSONObject)11 Body (retrofit2.http.Body)11