Search in sources :

Example 56 with Builder

use of okhttp3.FormBody.Builder in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method addExternalInterceptor.

/**
   * For OKHttpClient, since it does not expose any interface for us to check the raw response
   * stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
   * we use OKHttp inner interceptor list.
   * @param parseNetworkInterceptor
   */
@Override
/* package */
void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
    OkHttpClient.Builder builder = okHttpClient.newBuilder();
    builder.networkInterceptors().add(new Interceptor() {

        @Override
        public Response intercept(final Chain okHttpChain) throws IOException {
            Request okHttpRequest = okHttpChain.request();
            // Transfer OkHttpRequest to ParseHttpRequest
            final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
            // Capture OkHttpResponse
            final Capture<Response> okHttpResponseCapture = new Capture<>();
            final ParseHttpResponse parseResponse = parseNetworkInterceptor.intercept(new ParseNetworkInterceptor.Chain() {

                @Override
                public ParseHttpRequest getRequest() {
                    return parseRequest;
                }

                @Override
                public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
                    // Use OKHttpClient to send request
                    Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
                    Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
                    okHttpResponseCapture.set(okHttpResponse);
                    return getResponse(okHttpResponse);
                }
            });
            final Response okHttpResponse = okHttpResponseCapture.get();
            // Ideally we should build newOkHttpResponse only based on parseResponse, however
            // ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
            // we rely on the okHttpResponse to generate the builder and change the necessary info
            // inside
            Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
            // Set status
            newOkHttpResponseBuilder.code(parseResponse.getStatusCode()).message(parseResponse.getReasonPhrase());
            // Set headers
            if (parseResponse.getAllHeaders() != null) {
                for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
                    newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
                }
            }
            // Set body
            newOkHttpResponseBuilder.body(new ResponseBody() {

                @Override
                public MediaType contentType() {
                    if (parseResponse.getContentType() == null) {
                        return null;
                    }
                    return MediaType.parse(parseResponse.getContentType());
                }

                @Override
                public long contentLength() {
                    return parseResponse.getTotalSize();
                }

                @Override
                public BufferedSource source() {
                    // interceptor.
                    if (parseResponse.getContent() == null) {
                        return null;
                    }
                    return Okio.buffer(Okio.source(parseResponse.getContent()));
                }
            });
            return newOkHttpResponseBuilder.build();
        }
    });
    okHttpClient = builder.build();
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) IOException(java.io.IOException) Capture(bolts.Capture) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) ParseHttpResponse(com.parse.http.ParseHttpResponse) Interceptor(okhttp3.Interceptor) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 57 with Builder

use of okhttp3.FormBody.Builder in project MVCHelper by LuckyJayce.

the class NetworkExeption method toMessage.

private final String toMessage() {
    ResponseBody body = response.body();
    StringBuilder builder = new StringBuilder("url:").append(url);
    builder.append(" code:").append(httpCode);
    builder.append(" message:").append(response.message());
    if (body != null) {
        try {
            builder.append(" body:").append(body.string());
            body.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return builder.toString();
}
Also used : IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 58 with Builder

use of okhttp3.FormBody.Builder in project MVCHelper by LuckyJayce.

the class DeleteMethod method buildRequset.

@Override
protected Request.Builder buildRequset(String url, Map<String, Object> params) {
    FormBody.Builder builder = new FormBody.Builder();
    if (params != null) {
        for (Entry<String, ?> entry : params.entrySet()) {
            builder.add(entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    RequestBody formBody = builder.build();
    return new Request.Builder().url(url).delete(formBody);
}
Also used : FormBody(okhttp3.FormBody) RequestBody(okhttp3.RequestBody)

Example 59 with Builder

use of okhttp3.FormBody.Builder in project sonarqube by SonarSource.

the class WebhookCallerImpl method call.

@Override
public WebhookDelivery call(Webhook webhook, WebhookPayload payload) {
    WebhookDelivery.Builder builder = new WebhookDelivery.Builder();
    long startedAt = system.now();
    builder.setAt(startedAt).setPayload(payload).setWebhook(webhook);
    try {
        Request request = buildHttpRequest(webhook, payload);
        try (Response response = execute(request)) {
            builder.setHttpStatus(response.code());
            builder.setDurationInMs((int) (system.now() - startedAt));
        }
    } catch (Exception e) {
        builder.setError(e);
    }
    return builder.build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException)

Example 60 with Builder

use of okhttp3.FormBody.Builder in project Reader by TheKeeperOfPie.

the class Receiver method checkInbox.

public void checkInbox(final Context context, @Nullable final ArrayList<String> names) {
    final ArrayList<String> readNames;
    if (names == null) {
        readNames = new ArrayList<>();
    } else {
        readNames = names;
    }
    new Thread(new Runnable() {

        @Override
        public void run() {
            final Listing messages = new Listing();
            Account[] accounts = accountManager.getAccountsByType(Reddit.ACCOUNT_TYPE);
            for (Account account : accounts) {
                final AccountManagerFuture<Bundle> futureAuth = accountManager.getAuthToken(account, Reddit.AUTH_TOKEN_FULL_ACCESS, null, true, null, null);
                try {
                    Bundle bundle = futureAuth.getResult();
                    final String tokenAuth = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Request request = new Request.Builder().url(Reddit.OAUTH_URL + "/message/unread").header(Reddit.USER_AGENT, Reddit.CUSTOM_USER_AGENT).header(Reddit.AUTHORIZATION, Reddit.BEARER + tokenAuth).header(Reddit.CONTENT_TYPE, Reddit.CONTENT_TYPE_APP_JSON).get().build();
                    String response = okHttpClient.newCall(request).execute().body().string();
                    Listing listing = Listing.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class));
                    messages.addChildren(listing.getChildren());
                    Log.d(TAG, account.name + " checkInbox response: " + response);
                } catch (OperationCanceledException | AuthenticatorException | IOException e) {
                    e.printStackTrace();
                }
            }
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
            Thing thing = null;
            for (int index = 0; index < messages.getChildren().size(); index++) {
                thing = messages.getChildren().get(index);
                if (readNames.contains(thing.getName())) {
                    reddit.markRead(thing.getName()).subscribe(new ObserverEmpty<>());
                    thing = null;
                } else {
                    readNames.add(thing.getName());
                    break;
                }
            }
            if (thing == null) {
                notificationManager.cancel(NOTIFICATION_INBOX);
                return;
            }
            int titleSuffixResource = messages.getChildren().size() == 1 ? R.string.new_message : R.string.new_messages;
            CharSequence content = "";
            CharSequence author = "";
            CharSequence dest = "";
            if (thing instanceof Message) {
                content = ((Message) thing).getBodyHtml();
                author = ((Message) thing).getAuthor();
                dest = ((Message) thing).getDest();
            } else if (thing instanceof Comment) {
                content = ((Comment) thing).getBodyHtml();
                author = ((Comment) thing).getAuthor();
                dest = ((Comment) thing).getDest();
            }
            Intent intentActivity = new Intent(context, ActivityMain.class);
            intentActivity.putExtra(ActivityMain.ACCOUNT, dest);
            intentActivity.putExtra(ActivityMain.NAV_ID, R.id.item_inbox);
            intentActivity.putExtra(ActivityMain.NAV_PAGE, ControllerInbox.UNREAD);
            PendingIntent pendingIntentActivity = PendingIntent.getActivity(context, 0, intentActivity, PendingIntent.FLAG_CANCEL_CURRENT);
            Intent intentRecheckInbox = new Intent(INTENT_INBOX);
            intentRecheckInbox.putExtra(READ_NAMES, readNames);
            PendingIntent pendingIntentRecheckInbox = PendingIntent.getBroadcast(context, 0, intentRecheckInbox, PendingIntent.FLAG_CANCEL_CURRENT);
            Themer themer = new Themer(context);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.app_icon_white_outline).setContentTitle(messages.getChildren().size() + " " + context.getResources().getString(titleSuffixResource)).setContentText(context.getString(R.string.expand_to_read_first_message)).setStyle(new NotificationCompat.BigTextStyle().setSummaryText(context.getString(R.string.from) + " /u/" + author).bigText(content)).setContentIntent(pendingIntentActivity).addAction(new NotificationCompat.Action(R.drawable.ic_check_white_24dp, context.getString(R.string.mark_read), pendingIntentRecheckInbox)).setDeleteIntent(pendingIntentRecheckInbox).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_EMAIL).setColor(themer.getColorPrimary()).setLights(themer.getColorPrimary(), LED_MS_ON, LED_MS_OFF);
            notificationManager.notify(NOTIFICATION_INBOX, builder.build());
        }
    }).start();
}
Also used : Account(android.accounts.Account) Message(com.winsonchiu.reader.data.reddit.Message) OperationCanceledException(android.accounts.OperationCanceledException) NotificationManagerCompat(android.support.v4.app.NotificationManagerCompat) JsonNode(com.fasterxml.jackson.databind.JsonNode) NotificationCompat(android.support.v4.app.NotificationCompat) Thing(com.winsonchiu.reader.data.reddit.Thing) Comment(com.winsonchiu.reader.data.reddit.Comment) Bundle(android.os.Bundle) Request(okhttp3.Request) AuthenticatorException(android.accounts.AuthenticatorException) Themer(com.winsonchiu.reader.theme.Themer) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) IOException(java.io.IOException) Listing(com.winsonchiu.reader.data.reddit.Listing) PendingIntent(android.app.PendingIntent)

Aggregations

Request (okhttp3.Request)42 Response (okhttp3.Response)40 RequestBody (okhttp3.RequestBody)27 OkHttpClient (okhttp3.OkHttpClient)26 IOException (java.io.IOException)25 Test (org.junit.Test)17 Interceptor (okhttp3.Interceptor)9 File (java.io.File)8 URI (java.net.URI)7 X509TrustManager (javax.net.ssl.X509TrustManager)7 MultipartBody (okhttp3.MultipartBody)7 Map (java.util.Map)6 HttpUrl (okhttp3.HttpUrl)6 Provides (dagger.Provides)5 TestClients.clientRequest (keywhiz.TestClients.clientRequest)5 MediaType (okhttp3.MediaType)5 Retrofit (retrofit2.Retrofit)5 SSLContext (javax.net.ssl.SSLContext)4 TrustManager (javax.net.ssl.TrustManager)4 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)4