Search in sources :

Example 46 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project BillingDubbo by TonyJiangWJ.

the class FundInfoController method queryFundInfo.

@RequestMapping(value = "/fund/info/query", method = RequestMethod.POST)
public FundInfoQueryResponse queryFundInfo(@ModelAttribute("request") @Validated FundInfoQueryRequest request) {
    FundInfoQueryResponse response = ResponseUtil.success(new FundInfoQueryResponse());
    response.setFundCode(request.getFundCode());
    if (StringUtils.isEmpty(request.getPurchaseDate())) {
        Optional<String> fundName = redisUtils.hGet(FUND_INFO_HASH_KEY, FUND_INFO_KEY_PREFIX + request.getFundCode(), String.class);
        if (fundName.isPresent()) {
            response.setFundName(fundName.get());
            return response;
        }
        String queryUrl = String.format(fundValueQueryUrl, request.getFundCode());
        OkHttpClient client = new OkHttpClient.Builder().callTimeout(10, TimeUnit.SECONDS).build();
        Request req = new Request.Builder().url(queryUrl).build();
        try (Response res = client.newCall(req).execute()) {
            if (res.isSuccessful() && res.body() != null) {
                String responseBodyStr = res.body().string();
                responseBodyStr = responseBodyStr.replaceAll("jsonpgz\\(", "").replaceAll("\\);", "");
                logger.debug("responseBody: {}", responseBodyStr);
                JSONObject jsonObject = JSONObject.parseObject(responseBodyStr);
                response.setFundConfirmedDate(jsonObject.getString("jzrq"));
                response.setFundConfirmedValue(jsonObject.getString("dwjz"));
                response.setFundName(jsonObject.getString("name"));
                if (StringUtils.isNotEmpty(response.getFundName())) {
                    redisUtils.hSet(FUND_INFO_HASH_KEY, FUND_INFO_KEY_PREFIX + request.getFundCode(), response.getFundName());
                    return response;
                }
            }
        } catch (IOException e) {
            logger.error("获取基金:" + request.getFundCode() + " 估值信息失败", e);
        }
    }
    return ResponseUtil.dataNotExisting(response);
}
Also used : BaseResponse(com.tony.billing.response.BaseResponse) Response(okhttp3.Response) FundsExistenceCheckResponse(com.tony.billing.response.fund.FundsExistenceCheckResponse) FundInfoQueryResponse(com.tony.billing.response.fund.FundInfoQueryResponse) OkHttpClient(okhttp3.OkHttpClient) JSONObject(com.alibaba.fastjson.JSONObject) FundUpdateRequest(com.tony.billing.request.fund.FundUpdateRequest) FundAddRequest(com.tony.billing.request.fund.FundAddRequest) FundEnhanceRequest(com.tony.billing.request.fund.FundEnhanceRequest) FundDeleteRequest(com.tony.billing.request.fund.FundDeleteRequest) Request(okhttp3.Request) FundBatchAddRequest(com.tony.billing.request.fund.FundBatchAddRequest) FundsExistenceCheckRequest(com.tony.billing.request.fund.FundsExistenceCheckRequest) FundInfoQueryRequest(com.tony.billing.request.fund.FundInfoQueryRequest) FundInfoQueryResponse(com.tony.billing.response.fund.FundInfoQueryResponse) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 47 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project captcha by anji-plus.

the class RetrofitUtils method initOkHttp.

private OkHttpClient initOkHttp() {
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
    return new OkHttpClient().newBuilder().readTimeout(DEFAULT_TIME, // 设置读取超时时间
    TimeUnit.SECONDS).connectTimeout(DEFAULT_TIME, // 设置请求超时时间
    TimeUnit.SECONDS).writeTimeout(DEFAULT_TIME, // 设置写入超时时间
    TimeUnit.SECONDS).retryOnConnectionFailure(// 设置出现错误进行重新连接
    true).addInterceptor(httpLoggingInterceptor).build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Example 48 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project iGap-Android by KianIranian-STDG.

the class HttpRequest method download.

@WorkerThread
private void download(String jwtToken, DownloadObject fileStruct) {
    isDownloading = true;
    notifyDownloadStatus(HttpDownloader.DownloadStatus.DOWNLOADING);
    OkHttpClient client = OkHttpClientInstance.getInstance();
    String fileToken = fileStruct.fileToken;
    String qParam = "?selector=" + fileStruct.selector;
    String url = BASE_URL + fileToken + qParam;
    Request.Builder builder = new Request.Builder().url(url).addHeader("Authorization", jwtToken);
    if (fileStruct.offset > 0) {
        builder.addHeader("Range", "bytes=" + fileStruct.offset + "-" + fileStruct.fileSize);
    }
    FileLog.i("HttpRequest", "download Start with " + url + " range " + "bytes=" + fileStruct.offset + "-" + fileStruct.fileSize + " cashId: " + fileStruct.mainCacheId);
    Request request = builder.build();
    Response response = null;
    try (OutputStream os = new FileOutputStream(fileStruct.tempFile, true)) {
        call = client.newCall(request);
        response = call.execute();
        if (response.body() == null) {
            throw new Exception("Download body is null!");
        }
        if (response.isSuccessful()) {
            InputStream inputStream = response.body().byteStream();
            byte[] iv = new byte[16];
            // do not remove i :)
            int i = inputStream.read(iv, 0, 16);
            InputStream cipherInputStream = new CipherInputStream(inputStream, getCipher(iv, G.symmetricKey));
            byte[] data = new byte[4096];
            int count;
            long downloaded = fileStruct.offset;
            while ((count = cipherInputStream.read(data)) != -1) {
                downloaded += count;
                fileStruct.offset = downloaded;
                int t = (int) ((downloaded * 100) / fileStruct.fileSize);
                if (fileStruct.progress < t) {
                    fileStruct.progress = t;
                    onProgress(fileStruct.progress);
                }
                os.write(data, 0, count);
                if (cancelDownload.get()) {
                    safelyCancelDownload();
                    return;
                }
            }
            if (downloaded < fileStruct.fileSize) {
                // This is for any reason that connection have problem and stream returned -1 and the file downloaded incompletely.
                FileLog.e("HttpRequest", "Download " + fileStruct.fileToken + " with offset: " + fileStruct.offset + " retried");
                inputStream.close();
                cipherInputStream.close();
                os.close();
                if (response.body() != null) {
                    response.body().close();
                }
                download(jwtToken, fileStruct);
            }
            onDownloadCompleted();
            cipherInputStream.close();
        } else if (response.code() == 401) {
            // token is expired
            refreshAccessTokenAndRetry();
        } else {
            onError(new Exception("Download is not successful!"));
        }
    } catch (Exception e) {
        onError(e);
    } finally {
        if (response != null && response.body() != null) {
            response.body().close();
        }
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) CipherInputStream(javax.crypto.CipherInputStream) CipherInputStream(javax.crypto.CipherInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Request(okhttp3.Request) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Response(okhttp3.Response) FileOutputStream(java.io.FileOutputStream) WorkerThread(androidx.annotation.WorkerThread)

Example 49 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project SpaceLaunchNow-Android by ItsCalebJones.

the class RetroFitFragment method onCreate.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getActivity().getApplicationContext();
    // setup cache
    File httpCacheDirectory = new File(context.getCacheDir(), "responses");
    // 10 MiB
    int cacheSize = 10 * 1024 * 1024;
    Cache cache = new Cache(httpCacheDirectory, cacheSize);
    client = new OkHttpClient().newBuilder().addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR).cache(cache).build();
    newsClient = new OkHttpClient().newBuilder().addNetworkInterceptor(NEWS_REWRITE_CACHE_CONTROL_INTERCEPTOR).cache(cache).build();
    ListPreferences sharedPreference = ListPreferences.getInstance(context);
    String BASE_URL = sharedPreference.getNetworkEndpoint();
    String NEWS_URL = Constants.NEWS_BASE_URL;
    spaceLaunchNowRetrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(client).addConverterFactory(GsonConverterFactory.create(getGson())).build();
    newsRetrofit = new Retrofit.Builder().baseUrl(NEWS_URL).client(newsClient).addConverterFactory(GsonConverterFactory.create(getNewsGson())).build();
}
Also used : ListPreferences(me.calebjones.spacelaunchnow.common.prefs.ListPreferences) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) File(java.io.File) Cache(okhttp3.Cache)

Example 50 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project SpaceLaunchNow-Android by ItsCalebJones.

the class RetrofitBuilder method spaceLaunchNowClient.

private static OkHttpClient spaceLaunchNowClient(final String token) {
    OkHttpClient.Builder client = new OkHttpClient().newBuilder();
    client.connectTimeout(15, TimeUnit.SECONDS);
    client.readTimeout(15, TimeUnit.SECONDS);
    client.writeTimeout(15, TimeUnit.SECONDS);
    client.addInterceptor(chain -> {
        Request request = chain.request().newBuilder().addHeader("Authorization", "Token " + token).build();
        return chain.proceed(request);
    });
    return client.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request)

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)145 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