/** * Returns the URL that would be retrieved by following {@code link} from this URL, or null if * the resulting URL is not well-formed. */ public @Nullable HttpUrl resolve(String link) { Builder builder = newBuilder(link); return builder != null ? builder.build() : null; }
@Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request(); String host = this.host; if (host != null) { HttpUrl newUrl = request.url().newBuilder() .host(host) .build(); request = request.newBuilder() .url(newUrl) .build(); } return chain.proceed(request); } }
/** * Returns the URL that would be retrieved by following {@code link} from this URL, or null if * the resulting URL is not well-formed. */ public @Nullable HttpUrl resolve(String link) { Builder builder = newBuilder(link); return builder != null ? builder.build() : null; }
/** * Returns a string with containing this URL with its username, password, query, and fragment * stripped, and its path replaced with {@code /...}. For example, redacting {@code * http://username:password@example.com/path} returns {@code http://example.com/...}. */ public String redact() { return newBuilder("/...") .username("") .password("") .build() .toString(); }
private Request buildRequest(String hostname, int type) { Request.Builder requestBuilder = new Request.Builder().header("Accept", DNS_MESSAGE.toString()); ByteString query = DnsRecordCodec.encodeQuery(hostname, type); if (post) { requestBuilder = requestBuilder.url(url).post(RequestBody.create(DNS_MESSAGE, query)); } else { String encoded = query.base64Url().replace("=", ""); HttpUrl requestUrl = url.newBuilder().addQueryParameter("dns", encoded).build(); requestBuilder = requestBuilder.url(requestUrl); } return requestBuilder.build(); }
/** See https://api.slack.com/methods/rtm.start. */ public RtmStartResponse rtmStart(String accessToken) throws IOException { HttpUrl url = baseUrl.newBuilder("rtm.start") .addQueryParameter("token", accessToken) .build(); Request request = new Request.Builder() .url(url) .build(); Call call = httpClient.newCall(request); try (Response response = call.execute()) { JsonAdapter<RtmStartResponse> jsonAdapter = moshi.adapter(RtmStartResponse.class); return jsonAdapter.fromJson(response.body().source()); } }
void addQueryParam(String name, @Nullable String value, boolean encoded) { if (relativeUrl != null) { // Do a one-time combination of the built relative URL and the base URL. urlBuilder = baseUrl.newBuilder(relativeUrl); if (urlBuilder == null) { throw new IllegalArgumentException( "Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl); } relativeUrl = null; } if (encoded) { //noinspection ConstantConditions Checked to be non-null by above 'if' block. urlBuilder.addEncodedQueryParameter(name, value); } else { //noinspection ConstantConditions Checked to be non-null by above 'if' block. urlBuilder.addQueryParameter(name, value); } }
/** * Returns this URL as a {@link URI java.net.URI}. Because {@code URI} is more strict than this * class, the returned URI may be semantically different from this URL: * * <ul> * <li>Characters forbidden by URI like {@code [} and {@code |} will be escaped. * <li>Invalid percent-encoded sequences like {@code %xx} will be encoded like {@code %25xx}. * <li>Whitespace and control characters in the fragment will be stripped. * </ul> * * <p>These differences may have a significant consequence when the URI is interpreted by a * webserver. For this reason the {@linkplain URI URI class} and this method should be avoided. */ public URI uri() { String uri = newBuilder().reencodeForUri().toString(); try { return new URI(uri); } catch (URISyntaxException e) { // Unlikely edge case: the URI has a forbidden character in the fragment. Strip it & retry. try { String stripped = uri.replaceAll("[\\u0000-\\u001F\\u007F-\\u009F\\p{javaWhitespace}]", ""); return URI.create(stripped); } catch (Exception e1) { throw new RuntimeException(e); // Unexpected! } } }
/** See https://api.slack.com/methods/oauth.access. */ public OAuthSession exchangeCode(String code, HttpUrl redirectUrl) throws IOException { HttpUrl url = baseUrl.newBuilder("oauth.access") .addQueryParameter("client_id", clientId) .addQueryParameter("client_secret", clientSecret) .addQueryParameter("code", code) .addQueryParameter("redirect_uri", redirectUrl.toString()) .build(); Request request = new Request.Builder() .url(url) .build(); Call call = httpClient.newCall(request); try (Response response = call.execute()) { JsonAdapter<OAuthSession> jsonAdapter = moshi.adapter(OAuthSession.class); return jsonAdapter.fromJson(response.body().source()); } }
HttpUrl link = response.request().url().resolve(href); if (link == null) continue; // URL is either invalid or its scheme isn't http/https. queue.add(link.newBuilder().fragment(null).build());
private HttpUrl.Builder prepareUrlBuilder(WsRequest wsRequest) { String path = wsRequest.getPath(); return baseUrl .resolve(path.startsWith("/") ? path.replaceAll("^(/)+", "") : path) .newBuilder(); }
@Override public String get(String url, Map<String, String> queryParas) { okhttp3.HttpUrl.Builder urlBuilder = okhttp3.HttpUrl.parse(url).newBuilder(); for (Entry<String, String> entry : queryParas.entrySet()) { urlBuilder.addQueryParameter(entry.getKey(), entry.getValue()); } okhttp3.HttpUrl httpUrl = urlBuilder.build(); okhttp3.Request request = new okhttp3.Request.Builder().url(httpUrl).get().build(); return exec(request); }
/** * Returns a string with containing this URL with its username, password, query, and fragment * stripped, and its path replaced with {@code /...}. For example, redacting {@code * http://username:password@example.com/path} returns {@code http://example.com/...}. */ public String redact() { return newBuilder("/...") .username("") .password("") .build() .toString(); }
/** See https://api.slack.com/docs/oauth. */ public HttpUrl authorizeUrl(String scopes, HttpUrl redirectUrl, ByteString state, String team) { HttpUrl.Builder builder = baseUrl.newBuilder("/oauth/authorize") .addQueryParameter("client_id", clientId) .addQueryParameter("scope", scopes) .addQueryParameter("redirect_uri", redirectUrl.toString()) .addQueryParameter("state", state.base64()); if (team != null) { builder.addQueryParameter("team", team); } return builder.build(); }
public void logout() throws IOException { HttpUrl url = RuneLiteAPI.getApiBase().newBuilder() .addPathSegment("account") .addPathSegment("logout") .build(); logger.debug("Built URI: {}", url); Request request = new Request.Builder() .header(RuneLiteAPI.RUNELITE_AUTH, uuid.toString()) .url(url) .build(); try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute()) { logger.debug("Sent logout request"); } }
void delete(UUID uuid) throws IOException { HttpUrl url = RuneLiteAPI.getApiRoot().newBuilder() .addPathSegment("session") .addQueryParameter("session", uuid.toString()) .build(); Request request = new Request.Builder() .delete() .url(url) .build(); RuneLiteAPI.CLIENT.newCall(request).execute().close(); } }
private Request postSubmitForm(String username, String password) { return new Request.Builder() .url(HttpUrl.parse(BASE_WEB_URL) .newBuilder() .addPathSegment(SUBMIT_PATH) .build()) .post(new FormBody.Builder() .add(LOGIN_PARAM_ACCT, username) .add(LOGIN_PARAM_PW, password) .build()) .build(); }
private Request postReply(String parentId, String text, String username, String password) { return new Request.Builder() .url(HttpUrl.parse(BASE_WEB_URL) .newBuilder() .addPathSegment(COMMENT_PATH) .build()) .post(new FormBody.Builder() .add(LOGIN_PARAM_ACCT, username) .add(LOGIN_PARAM_PW, password) .add(COMMENT_PARAM_PARENT, parentId) .add(COMMENT_PARAM_TEXT, text) .build()) .build(); }
@Test public void send_basic_authentication_header_if_url_contains_credentials() throws Exception { HttpUrl url = server.url("/ping").newBuilder().username("theLogin").password("thePassword").build(); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, RandomStringUtils.randomAlphanumeric(40),"my-webhook", url.toString()); server.enqueue(new MockResponse().setBody("pong")); WebhookDelivery delivery = newSender().call(webhook, PAYLOAD); assertThat(delivery.getWebhook().getUrl()) .isEqualTo(url.toString()) .contains("://theLogin:thePassword@"); RecordedRequest recordedRequest = takeAndVerifyPostRequest("/ping"); assertThat(recordedRequest.getHeader("Authorization")).isEqualTo(Credentials.basic(url.username(), url.password())); }
@Test public void credentials_are_propagated_to_POST_redirects() throws Exception { HttpUrl url = server.url("/redirect").newBuilder().username("theLogin").password("thePassword").build(); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, RandomStringUtils.randomAlphanumeric(40),"my-webhook", url.toString()); // /redirect redirects to /target server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", server.url("target"))); server.enqueue(new MockResponse().setResponseCode(200)); WebhookDelivery delivery = newSender().call(webhook, PAYLOAD); assertThat(delivery.getHttpStatus().get()).isEqualTo(200); RecordedRequest redirectedRequest = takeAndVerifyPostRequest("/redirect"); assertThat(redirectedRequest.getHeader("Authorization")).isEqualTo(Credentials.basic(url.username(), url.password())); RecordedRequest targetRequest = takeAndVerifyPostRequest("/target"); assertThat(targetRequest.getHeader("Authorization")).isEqualTo(Credentials.basic(url.username(), url.password())); }