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);
}
}
}
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);
});
}
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;
}
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);
}
}
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();
}
Aggregations