Search in sources :

Example 86 with Builder

use of okhttp3.HttpUrl.Builder in project nzbhydra2 by theotherp.

the class WebAccess method callUrl.

public String callUrl(String url, Map<String, String> headers, int timeout) throws IOException {
    Builder builder = new Builder().url(url);
    for (Entry<String, String> entry : headers.entrySet()) {
        builder.addHeader(entry.getKey(), entry.getValue());
    }
    Request request = builder.build();
    OkHttpClient client = requestFactory.getOkHttpClientBuilder(request.url().uri()).readTimeout(timeout, TimeUnit.SECONDS).connectTimeout(timeout, TimeUnit.SECONDS).writeTimeout(timeout, TimeUnit.SECONDS).build();
    logger.debug(LoggingMarkers.HTTP, "Calling URL {} with headers {} and timeout{}", url, headers.entrySet().stream().map(x -> x.getKey() + ":" + x.getValue()).collect(Collectors.joining(", ")), timeout);
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            String error = String.format("URL call to %s returned %d: %s", url, response.code(), response.message());
            logger.error(error);
            throw new IOException(error);
        }
        String body = response.body().string();
        logger.debug(LoggingMarkers.HTTP, "Call to {} successful with content length {} and headers {}", url, body.length(), response.headers());
        response.body().close();
        return body;
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Builder(okhttp3.Request.Builder) Request(okhttp3.Request) IOException(java.io.IOException)

Example 87 with Builder

use of okhttp3.HttpUrl.Builder in project nzbhydra2 by theotherp.

the class FromPythonMigration method callHydraUrl.

protected OkHttpResponse callHydraUrl(String nzbhydra1BaseUrl, String internalApiPath) {
    try {
        UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(nzbhydra1BaseUrl);
        urlBuilder.pathSegment("internalapi", internalApiPath).toUriString();
        String url = urlBuilder.toUriString();
        logger.info("Connecting to URL {}", url);
        Request request = new Builder().url(url).build();
        OkHttpClient.Builder clientBuilder = requestFactory.getOkHttpClientBuilder(request.url().uri());
        String userInfo = urlBuilder.build().toUri().getUserInfo();
        if (!Strings.isNullOrEmpty(userInfo)) {
            clientBuilder = clientBuilder.authenticator(new Authenticator() {

                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    String[] userAndPass = userInfo.split(":");
                    return response.request().newBuilder().header("Authorization", Credentials.basic(userAndPass[0], userAndPass[1])).build();
                }
            });
        }
        try (Response response = clientBuilder.build().newCall(request).execute()) {
            return new OkHttpResponse(response.body().string(), response.isSuccessful(), response.message());
        }
    } catch (Exception e) {
        return new OkHttpResponse("", false, e.getMessage());
    }
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) Builder(okhttp3.Request.Builder) IOException(java.io.IOException)

Example 88 with Builder

use of okhttp3.HttpUrl.Builder in project nzbhydra2 by theotherp.

the class WebHooks method onNzbDownloadEvent.

@Async
@EventListener
public void onNzbDownloadEvent(FileDownloadEvent downloadEvent) throws IOException {
    String downloadHook = System.getProperty("nzbhydra.hooks.download");
    if (!Strings.isNullOrEmpty(downloadHook)) {
        if (downloadEvent.getDownloadEntity().getAccessSource() == SearchSource.INTERNAL) {
            try {
                OkHttpClient client = requestFactory.getOkHttpClientBuilder(URI.create(downloadHook)).build();
                String content = objectMapper.writeValueAsString(downloadEvent.getDownloadEntity());
                Response response = client.newCall(new Builder().url(downloadHook).method("PUT", RequestBody.create(MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE), content)).build()).execute();
                response.close();
                logger.debug("Called download web hook with response {}", response);
            } catch (IOException e) {
                logger.error("Unable to execute webhook to {} on download event", downloadHook);
            }
        }
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Builder(okhttp3.Request.Builder) IOException(java.io.IOException) Async(org.springframework.scheduling.annotation.Async) EventListener(org.springframework.context.event.EventListener)

Example 89 with Builder

use of okhttp3.HttpUrl.Builder in project nzbhydra2 by theotherp.

the class CustomTmdb method okHttpClient.

@Override
protected synchronized OkHttpClient okHttpClient() {
    if (client == null) {
        try {
            Builder builder = requestFactory.getOkHttpClientBuilder(new URI(Tmdb.API_URL));
            setOkHttpClientDefaults(builder);
            client = builder.build();
        } catch (URISyntaxException e) {
            throw new RuntimeException("Shouldn't happen...", e);
        }
    }
    return client;
}
Also used : Builder(okhttp3.OkHttpClient.Builder) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 90 with Builder

use of okhttp3.HttpUrl.Builder in project nzbhydra2 by theotherp.

the class ExternalApiSearchingIntegrationTest method shouldCallNewznabTwice.

@Test
public void shouldCallNewznabTwice() throws Exception {
    NewznabResponseBuilder builder = new NewznabResponseBuilder();
    String xml1 = builder.getTestResult(1, 100, "indexer1", 0, 150).toXmlString();
    String xml2 = builder.getTestResult(101, 150, "indexer1", 100, 150).toXmlString();
    String xml3 = builder.getTestResult(1, 0, "indexer2", 0, 0).toXmlString();
    webServer.enqueue(new MockResponse().setBody(xml1).setHeader("Content-Type", "application/xml; charset=utf-8"));
    webServer.enqueue(new MockResponse().setBody(xml2).setHeader("Content-Type", "application/xml; charset=utf-8"));
    webServer.enqueue(new MockResponse().setBody(xml3).setHeader("Content-Type", "application/xml; charset=utf-8"));
    NewznabParameters apiCallParameters = new NewznabParameters();
    apiCallParameters.setApikey("apikey");
    apiCallParameters.setOffset(0);
    apiCallParameters.setLimit(100);
    apiCallParameters.setT(ActionAttribute.SEARCH);
    NewznabXmlRoot apiSearchResult = (NewznabXmlRoot) externalApi.api(apiCallParameters).getBody();
    assertThat(apiSearchResult.getRssChannel().getItems().size()).isEqualTo(100);
    apiCallParameters.setLimit(100);
    apiCallParameters.setOffset(100);
    apiSearchResult = (NewznabXmlRoot) externalApi.api(apiCallParameters).getBody();
    assertThat(apiSearchResult.getRssChannel().getItems().size()).isEqualTo(50);
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) NewznabXmlRoot(org.nzbhydra.mapping.newznab.xml.NewznabXmlRoot) NewznabResponseBuilder(org.nzbhydra.fortests.NewznabResponseBuilder) NewznabParameters(org.nzbhydra.mapping.newznab.NewznabParameters) Test(org.junit.Test) AbstractConfigReplacingTest(org.nzbhydra.tests.AbstractConfigReplacingTest) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

Request (okhttp3.Request)206 Response (okhttp3.Response)148 OkHttpClient (okhttp3.OkHttpClient)142 IOException (java.io.IOException)111 RequestBody (okhttp3.RequestBody)81 Test (org.junit.Test)75 HttpUrl (okhttp3.HttpUrl)47 File (java.io.File)42 MockResponse (okhttp3.mockwebserver.MockResponse)42 MultipartBody (okhttp3.MultipartBody)40 Map (java.util.Map)39 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)31 Call (okhttp3.Call)29 Interceptor (okhttp3.Interceptor)29 Retrofit (retrofit2.Retrofit)29 Builder (okhttp3.OkHttpClient.Builder)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)25 ResponseBody (okhttp3.ResponseBody)24 HashMap (java.util.HashMap)22 FormBody (okhttp3.FormBody)21