Search in sources :

Example 21 with Builder

use of okhttp3.Request.Builder in project PokeGOAPI-Java by Grover-c13.

the class PtcCredentialProvider method login.

/**
	 * Starts a login flow for pokemon.com (PTC) using a username and password,
	 * this uses pokemon.com's oauth endpoint and returns a usable AuthInfo without user interaction
	 *
	 * @param username PTC username
	 * @param password PTC password
	 * @param attempt the current attempt index
	 * @throws LoginFailedException if an exception occurs while attempting to log in
	 * @throws InvalidCredentialsException if invalid credentials are used
	 */
private void login(String username, String password, int attempt) throws LoginFailedException, InvalidCredentialsException {
    try {
        //TODO: stop creating an okhttp client per request
        Request get = new Request.Builder().url(LOGIN_URL).get().build();
        Response getResponse;
        try {
            getResponse = client.newCall(get).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Failed to receive contents from server", e);
        }
        Moshi moshi = new Moshi.Builder().build();
        PtcAuthJson ptcAuth;
        try {
            String response = getResponse.body().string();
            ptcAuth = moshi.adapter(PtcAuthJson.class).fromJson(response);
        } catch (IOException e) {
            throw new LoginFailedException("Looks like the servers are down", e);
        }
        HttpUrl url = HttpUrl.parse(LOGIN_URL).newBuilder().addQueryParameter("lt", ptcAuth.getLt()).addQueryParameter("execution", ptcAuth.getExecution()).addQueryParameter("_eventId", "submit").addQueryParameter("username", username).addQueryParameter("password", password).build();
        RequestBody reqBody = RequestBody.create(null, new byte[0]);
        Request postRequest = new Request.Builder().url(url).method("POST", reqBody).build();
        // Need a new client for this to not follow redirects
        Response response;
        try {
            response = client.newBuilder().followRedirects(false).followSslRedirects(false).build().newCall(postRequest).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Network failure", e);
        }
        String body;
        try {
            body = response.body().string();
        } catch (IOException e) {
            throw new LoginFailedException("Response body fetching failed", e);
        }
        if (body.length() > 0) {
            PtcError ptcError;
            try {
                ptcError = moshi.adapter(PtcError.class).fromJson(body);
            } catch (IOException e) {
                throw new LoginFailedException("Unmarshalling failure", e);
            }
            if (ptcError.getError() != null && ptcError.getError().length() > 0) {
                throw new InvalidCredentialsException(ptcError.getError());
            } else if (ptcError.getErrors().length > 0) {
                StringBuilder builder = new StringBuilder();
                String[] errors = ptcError.getErrors();
                for (int i = 0; i < errors.length - 1; i++) {
                    String error = errors[i];
                    builder.append("\"").append(error).append("\", ");
                }
                builder.append("\"").append(errors[errors.length - 1]).append("\"");
                throw new InvalidCredentialsException(builder.toString());
            }
        }
        String ticket = null;
        for (String location : response.headers("location")) {
            String[] ticketArray = location.split("ticket=");
            if (ticketArray.length > 1) {
                ticket = ticketArray[1];
            }
        }
        if (ticket == null) {
            throw new LoginFailedException("Failed to fetch token, body:" + body);
        }
        url = HttpUrl.parse(LOGIN_OAUTH).newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("redirect_uri", REDIRECT_URI).addQueryParameter("client_secret", CLIENT_SECRET).addQueryParameter("grant_type", "refreshToken").addQueryParameter("code", ticket).build();
        postRequest = new Request.Builder().url(url).method("POST", reqBody).build();
        try {
            response = client.newCall(postRequest).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Network Failure ", e);
        }
        try {
            body = response.body().string();
        } catch (IOException e) {
            throw new LoginFailedException("Network failure", e);
        }
        String[] params;
        try {
            params = body.split("&");
            int expire = Integer.valueOf(params[1].split("=")[1]);
            tokenId = params[0].split("=")[1];
            expiresTimestamp = time.currentTimeMillis() + (expire * 1000 - REFRESH_TOKEN_BUFFER_TIME);
            unknown2 = expire;
            if (random.nextDouble() > 0.1) {
                unknown2 = UK2_VALUES[random.nextInt(UK2_VALUES.length)];
            }
        } catch (Exception e) {
            throw new LoginFailedException("Failed to fetch token, body:" + body);
        }
    } catch (LoginFailedException e) {
        if (shouldRetry && attempt < MAXIMUM_RETRIES) {
            login(username, password, ++attempt);
        }
    }
}
Also used : Moshi(com.squareup.moshi.Moshi) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) IOException(java.io.IOException) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) RequestBody(okhttp3.RequestBody)

Example 22 with Builder

use of okhttp3.Request.Builder in project AntennaPod by AntennaPod.

the class ProxyDialog method test.

private void test() {
    if (subscription != null) {
        subscription.unsubscribe();
    }
    if (!checkValidity()) {
        setTestRequired(true);
        return;
    }
    TypedArray res = context.getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary });
    int textColorPrimary = res.getColor(0, 0);
    res.recycle();
    String checking = context.getString(R.string.proxy_checking);
    txtvMessage.setTextColor(textColorPrimary);
    txtvMessage.setText("{fa-circle-o-notch spin} " + checking);
    txtvMessage.setVisibility(View.VISIBLE);
    subscription = Observable.create(new Observable.OnSubscribe<Response>() {

        @Override
        public void call(Subscriber<? super Response> subscriber) {
            String type = (String) spType.getSelectedItem();
            String host = etHost.getText().toString();
            String port = etPort.getText().toString();
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();
            int portValue = 8080;
            if (!TextUtils.isEmpty(port)) {
                portValue = Integer.valueOf(port);
            }
            SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
            Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
            Proxy proxy = new Proxy(proxyType, address);
            OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).proxy(proxy);
            builder.interceptors().clear();
            OkHttpClient client = builder.build();
            if (!TextUtils.isEmpty(username)) {
                String credentials = Credentials.basic(username, password);
                client.interceptors().add(chain -> {
                    Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                    return chain.proceed(request);
                });
            }
            Request request = new Request.Builder().url("http://www.google.com").head().build();
            try {
                Response response = client.newCall(request).execute();
                subscriber.onNext(response);
            } catch (IOException e) {
                subscriber.onError(e);
            }
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(response -> {
        int colorId;
        String icon;
        String result;
        if (response.isSuccessful()) {
            colorId = R.color.download_success_green;
            icon = "{fa-check}";
            result = context.getString(R.string.proxy_test_successful);
        } else {
            colorId = R.color.download_failed_red;
            icon = "{fa-close}";
            result = context.getString(R.string.proxy_test_failed);
        }
        int color = ContextCompat.getColor(context, colorId);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, response.message());
        txtvMessage.setText(message);
        setTestRequired(!response.isSuccessful());
    }, error -> {
        String icon = "{fa-close}";
        String result = context.getString(R.string.proxy_test_failed);
        int color = ContextCompat.getColor(context, R.color.download_failed_red);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, error.getMessage());
        txtvMessage.setText(message);
        setTestRequired(true);
    });
}
Also used : Context(android.content.Context) SocketAddress(java.net.SocketAddress) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Dialog(android.app.Dialog) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) Observable(rx.Observable) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) MDButton(com.afollestad.materialdialogs.internal.MDButton) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Response(okhttp3.Response) AdapterView(android.widget.AdapterView) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) Subscriber(rx.Subscriber) R(de.danoeh.antennapod.R) ContextCompat(android.support.v4.content.ContextCompat) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Subscription(rx.Subscription) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) Proxy(java.net.Proxy) TypedArray(android.content.res.TypedArray) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 23 with Builder

use of okhttp3.Request.Builder in project AntennaPod by AntennaPod.

the class AntennapodHttpClient method newBuilder.

/**
     * Creates a new HTTP client.  Most users should just use
     * getHttpClient() to get the standard AntennaPod client,
     * but sometimes it's necessary for others to have their own
     * copy so that the clients don't share state.
     * @return http client
     */
@NonNull
public static OkHttpClient.Builder newBuilder() {
    Log.d(TAG, "Creating new instance of HTTP client");
    System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // detect 301 Moved permanently and 308 Permanent Redirect
    builder.networkInterceptors().add(chain -> {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == HttpURLConnection.HTTP_MOVED_PERM || response.code() == StatusLine.HTTP_PERM_REDIRECT) {
            String location = response.header("Location");
            if (location.startsWith("/")) {
                HttpUrl url = request.url();
                location = url.scheme() + "://" + url.host() + location;
            } else if (!location.toLowerCase().startsWith("http://") && !location.toLowerCase().startsWith("https://")) {
                HttpUrl url = request.url();
                String path = url.encodedPath();
                String newPath = path.substring(0, path.lastIndexOf("/") + 1) + location;
                location = url.scheme() + "://" + url.host() + newPath;
            }
            try {
                DBWriter.updateFeedDownloadURL(request.url().toString(), location).get();
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
        return response;
    });
    // set cookie handler
    CookieManager cm = new CookieManager();
    cm.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
    builder.cookieJar(new JavaNetCookieJar(cm));
    // set timeouts
    builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    // configure redirects
    builder.followRedirects(true);
    builder.followSslRedirects(true);
    ProxyConfig config = UserPreferences.getProxyConfig();
    if (config.type != Proxy.Type.DIRECT) {
        int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
        SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
        Proxy proxy = new Proxy(config.type, address);
        builder.proxy(proxy);
        if (!TextUtils.isEmpty(config.username)) {
            String credentials = Credentials.basic(config.username, config.password);
            builder.interceptors().add(chain -> {
                Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                return chain.proceed(request);
            });
        }
    }
    if (16 <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < 21) {
        builder.sslSocketFactory(new CustomSslSocketFactory(), trustManager());
    }
    return builder;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) Response(okhttp3.Response) Proxy(java.net.Proxy) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) CookieManager(java.net.CookieManager) NonNull(android.support.annotation.NonNull)

Example 24 with Builder

use of okhttp3.Request.Builder 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 25 with Builder

use of okhttp3.Request.Builder in project amhttp by Eddieyuan123.

the class RequestBodyFactoryImpl method buildRequestBody.

@Override
public RequestBody buildRequestBody(File file, String fileName, HashMap<String, String> params) {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    if (params == null) {
        throw new NullPointerException("requestBodyFactory build params is null");
    } else {
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        try {
            if (params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    builder.addFormDataPart(entry.getKey(), entry.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", fileName, fileBody);
    }
    return builder.build();
}
Also used : MultipartBody(okhttp3.MultipartBody) Map(java.util.Map) HashMap(java.util.HashMap) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)163 Response (okhttp3.Response)120 OkHttpClient (okhttp3.OkHttpClient)91 IOException (java.io.IOException)83 RequestBody (okhttp3.RequestBody)67 Test (org.junit.Test)67 MultipartBody (okhttp3.MultipartBody)35 File (java.io.File)31 Map (java.util.Map)31 MockResponse (okhttp3.mockwebserver.MockResponse)31 HttpUrl (okhttp3.HttpUrl)29 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)27 Call (okhttp3.Call)25 Interceptor (okhttp3.Interceptor)24 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)22 Retrofit (retrofit2.Retrofit)20 Builder (okhttp3.Request.Builder)19 ResponseBody (okhttp3.ResponseBody)18 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)17 Builder (okhttp3.OkHttpClient.Builder)17