Search in sources :

Example 1 with OkHttpClient

use of org.testcontainers.shaded.okhttp3.OkHttpClient in project Manhua by ag2s20150909.

the class HttpTool method httpGet.

public static String httpGet(String url) {
    OkHttpClient.Builder buider = new OkHttpClient.Builder();
    OkHttpClient client = buider.build();
    Request.Builder requestbuilder = new Request.Builder().get().url(url);
    requestbuilder.header("Referer", "m.pufei8.com/");
    requestbuilder.header("User-Agent", WebSettings.getDefaultUserAgent(APP.getContext()));
    Request request = requestbuilder.build();
    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return new String(Objects.requireNonNull(response.body()).bytes(), "gb2312");
        } else {
            return "error:" + response.message() + " errorcode:" + response.code();
        }
    } catch (Exception e) {
        return "error:" + e.getMessage();
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 2 with OkHttpClient

use of org.testcontainers.shaded.okhttp3.OkHttpClient in project fabric8-maven-plugin by fabric8io.

the class IoUtil method download.

/**
 * Download with showing the progress a given URL and store it in a file
 * @param log logger used to track progress
 * @param downloadUrl url to download
 * @param target target file where to store the downloaded data
 * @throws MojoExecutionException
 */
public static void download(Logger log, URL downloadUrl, File target) throws MojoExecutionException {
    log.progressStart();
    try {
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(30, TimeUnit.MINUTES).build();
        Request request = new Request.Builder().url(downloadUrl).build();
        Response response = client.newCall(request).execute();
        try (OutputStream out = new FileOutputStream(target);
            InputStream im = response.body().byteStream()) {
            long length = response.body().contentLength();
            InputStream in = response.body().byteStream();
            byte[] buffer = new byte[8192];
            long readBytes = 0;
            while (true) {
                int len = in.read(buffer);
                readBytes += len;
                log.progressUpdate(target.getName(), "Downloading", getProgressBar(readBytes, length));
                if (len <= 0) {
                    out.flush();
                    break;
                }
                out.write(buffer, 0, len);
            }
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to download URL " + downloadUrl + " to  " + target + ": " + e, e);
    } finally {
        log.progressFinished();
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) Request(okhttp3.Request) IOException(java.io.IOException)

Example 3 with OkHttpClient

use of org.testcontainers.shaded.okhttp3.OkHttpClient in project crnk-framework by crnk-project.

the class BasicRepositoryAccessTestBase method testJsonApiResponseContentTypeReceived.

@Test
public void testJsonApiResponseContentTypeReceived() throws IOException {
    String url = testContainer.getBaseUrl() + "/schedules";
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    Assert.assertEquals(removeWhiteSpace(HttpHeaders.JSONAPI_CONTENT_TYPE_AND_CHARSET), removeWhiteSpace(response.header(HttpHeaders.HTTP_CONTENT_TYPE)));
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Test(org.junit.Test)

Example 4 with OkHttpClient

use of org.testcontainers.shaded.okhttp3.OkHttpClient in project natural-voice-mobile-sdk-android by aimmatic.

the class Language method loadLanguage.

@VisibleForTesting
static void loadLanguage(final AppContext appContext, final Callback callback) {
    OkHttpClient client = appContext.getOkHttpClient();
    final Request request = new Request.Builder().url(appContext.getHost() + Resources.ApiVersion + Resources.NaturalVoiceLanguage).build();
    final File dir = appContext.getDataDir();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            if (callback != null)
                callback.onFailure(call, e);
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            if (response.code() == 200 && response.body() != null) {
                ResponseBody responseBody = response.body();
                BufferedSource source = responseBody.source();
                // request the entire body.
                source.request(Long.MAX_VALUE);
                Buffer buffer = source.buffer();
                String resp = buffer.clone().readString(Charset.forName("UTF-8"));
                LangResponse lr = new Gson().fromJson(resp, LangResponse.class);
                File file = new File(dir, "aimmatic-speech-lang.json");
                FileOutputStream out = new FileOutputStream(file);
                String data = new Gson().toJson(lr.getLanguages());
                out.write(data.getBytes());
                out.close();
            }
            if (callback != null)
                callback.onResponse(call, response);
        }
    });
}
Also used : Buffer(okio.Buffer) Call(okhttp3.Call) LangResponse(com.aimmatic.natural.voice.rest.response.LangResponse) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Gson(com.google.gson.Gson) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) LangResponse(com.aimmatic.natural.voice.rest.response.LangResponse) Response(okhttp3.Response) Callback(okhttp3.Callback) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedSource(okio.BufferedSource) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 5 with OkHttpClient

use of org.testcontainers.shaded.okhttp3.OkHttpClient in project natural-voice-mobile-sdk-android by aimmatic.

the class AimMatic method fetchToken.

/**
 * Fetch token retrieve a token from an exchange code after user successfully logged using
 * AimMatic account.
 *
 * @param code     a valid exchange code
 * @param apiKey   a valid api key
 * @param callback a callback function to notice when request is success or failure
 */
public static void fetchToken(String code, String apiKey, final Callback<AccessToken> callback) {
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(String.format("%s/v1/exchange?code=%s", service, code)).addHeader("Authorization", "AimMatic " + apiKey).build();
    okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            callback.onError(e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                TokenResponse tokenResponse = new Gson().fromJson(response.body().string(), TokenResponse.class);
                callback.onSuccess(tokenResponse.getAccessToken());
            } catch (Exception e) {
                if (response.code() != 200) {
                    callback.onError(new Exception("Server reply with status " + response.code()));
                } else {
                    callback.onError(e);
                }
            }
        }
    });
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Gson(com.google.gson.Gson) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)1944 Request (okhttp3.Request)1024 Response (okhttp3.Response)880 IOException (java.io.IOException)567 Test (org.junit.Test)365 Call (okhttp3.Call)290 RequestBody (okhttp3.RequestBody)222 Test (org.junit.jupiter.api.Test)144 Retrofit (retrofit2.Retrofit)138 File (java.io.File)132 HttpUrl (okhttp3.HttpUrl)131 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)128 Callback (okhttp3.Callback)117 JSONObject (org.json.JSONObject)110 ArrayList (java.util.ArrayList)106 ResponseBody (okhttp3.ResponseBody)105 Gson (com.google.gson.Gson)98 MediaType (okhttp3.MediaType)98 List (java.util.List)92 Map (java.util.Map)85