标签: okhttp

使用OkHttp进行缓存(不使用Retrofit)

在我的Application onCreate中,我正在创建一个10MB的缓存:

try
{
    File httpCacheDir = new File(getApplicationContext().getCacheDir(), Constants.AppName);
    long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
    HttpResponseCache.install(httpCacheDir, httpCacheSize);
}
catch (IOException ex)
{
    Log.i(Constants.AppName, "HTTP response cache installation failed: " + ex);
}
Run Code Online (Sandbox Code Playgroud)

我对资源的调用:

OkHttpClient client = new OkHttpClient();
client.setResponseCache(HttpResponseCache.getInstalled());

HttpURLConnection connection = client.open(url);
connection.addRequestProperty("Cache-Control", "max-age=60");
InputStream inputStream = connection.getInputStream();
Run Code Online (Sandbox Code Playgroud)

我将在10秒内彼此初始化此调用两次,并且OkHttp-Response-Source标头始终为NETWORK 200.

for (Map.Entry<String, List<String>> k : connection.getHeaderFields().entrySet())
{
    for (String v : k.getValue())
    {
        Log.d(Constants.AppName, k.getKey() + ": " + v);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

android okhttp

1
推荐指数
1
解决办法
3051
查看次数

Okhttp发布JSON数组

我正在尝试发布一个帖子。

        RequestBody formBody = new FormBody.Builder()
            .add("userId", userId)
            .add("patientName", patient.getName())
            .add("patientDob", patient.getDOB())
            .add("referralFor", patient.getFor())
            .add("patientPhoto", "")
            .add("message", "test")
            .add("referralParticipants", )
            .build();
Run Code Online (Sandbox Code Playgroud)

但是ReferralParticipants是一个json数组。这也可能是动态的。我不确定如何执行此操作,因为表单数据中没有任何内容,似乎只是发送了原始的json?

在此处输入图片说明

android json okhttp

1
推荐指数
1
解决办法
1652
查看次数

Okhttp3没有在Android Studio中看到WebSocket接口

我在okhttp3 lib中遇到了一些问题.

我在gradle文件依赖项中添加了以下行:

compile 'com.squareup.okhttp3:okhttp:3.4.1'
Run Code Online (Sandbox Code Playgroud)

之后,我尝试创建webSocket连接,如okhttp websocket示例,但在Android Studio中,我没有看到任何类和接口,如

import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
Run Code Online (Sandbox Code Playgroud)

但我知道这些文件存在于okhttp3中.谁能解释我做错了什么?

如果我们在okhttp javadoc中看到我们找不到这些类.但他们在github.

java android square okhttp okhttp3

1
推荐指数
1
解决办法
935
查看次数

带有 OkHttp 的意外主机

我正在尝试通过 get 请求发送查询,问题是我不断收到 java.lang.IllegalArgumentException: unexpected host

   HttpUrl url = new HttpUrl.Builder()
            .scheme("http")
            .host("10.0.2.2" + "/api/" + 7) // This is where the error is coming in
            .addQueryParameter("lat", deviceLat[0])
            .addQueryParameter("long", deviceLong[0])
            .build();


    Request request = new Request.Builder()
            .url(url)
            .build();
Run Code Online (Sandbox Code Playgroud)

感谢所有帮助:)

android get okhttp

1
推荐指数
1
解决办法
4571
查看次数

如何使用 Glide 和 OkHttp 获取 http 响应头

我需要从图像中获取 http 响应标头。如何为 Glide 的每个请求创建拦截器?是否有必要创建一个 Glide 模块?

java android okhttp android-glide

1
推荐指数
1
解决办法
2648
查看次数

握手失败使用 okHttp 但使用 HttpURLConnection

我正在尝试向服务器发送 get 请求(发送 get 请求进行测试,实际上我需要向同一台服务器发送一个 post 请求。如果 get 有效,post 将起作用)

服务器链接是 https://bits-bosm.org/2017/registrations/signup/

问题是当我使用 okHttp 发送请求时,我收到一个失败响应,说握手失败。

这是我用来使用 okHttp 发送请求的代码(在 kotlin 中)

val request = Request.Builder()
            .url("https://bits-bosm.org/2017/registrations/signup/")
            .build()

    okHttpClient.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call?, e: IOException?) {
            val mMessage = e?.message?.toString()
            Log.w("failure Response", mMessage)
        }

        override fun onResponse(call: Call?, response: Response?) {
            val mMessage = response?.body()?.string()
            Log.e("Message", mMessage)
        }
    })
Run Code Online (Sandbox Code Playgroud)

但是如果我使用 HttpUrlConnection 将获取请求发送到同一台服务器,我会得到响应。

这是相同的代码(java)

private static final String USER_AGENT = "Mozilla/5.0";

private static final String GET_URL = "https://bits-bosm.org/2017/registrations/signup/";



static void …
Run Code Online (Sandbox Code Playgroud)

ssl android httpurlconnection okhttp

1
推荐指数
1
解决办法
2350
查看次数

如何忽略Okhttp中的SSL错误?

我已经安装并打开PacketCapture,然后当我使用Okhttp向服务器请求API时,出现此异常。

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Run Code Online (Sandbox Code Playgroud)

是否可以忽略SSL错误?

java ssl android okhttp

1
推荐指数
1
解决办法
3771
查看次数

成功刷新令牌请求后,OkHttp Authenticator循环

我实现了okhttp3.Authenticator与Retrofit 2一起扩展的类,用于处理android应用程序中的401错误。它应该调用refreshToken request,然后如果成功,则使用新的访问令牌重新调用所需的请求。问题是成功获取刷新令牌后,我的TokenAuthenticator...会一次又一次刷新令牌,直到达到某个限制。你有什么线索吗?

TokenAuthenticator类:

class TokenAuthenticator : Authenticator {

    private val notLoggedResponseCode = 401
    private val successResponseCode = 200
    private val refreshTokenGrantType = "refresh_token"

    override fun authenticate(route: Route?, response: okhttp3.Response?): Request? {

        if (response?.code() == notLoggedResponseCode) {

            val refreshTokenResponse: Response<Authorization> = RestController
                    .getInstance()
                    .basicRetrofit
                    .create(AuthRepository::class.java)
                    .refreshToken(
                            Credentials.basic(BuildConfig.CLIENT_ID, BuildConfig.CLIENT_SECRET),
                            refreshTokenGrantType,
                            UserSession.getInstance().authorization?.refreshToken!!)
                    .execute()



            return if (refreshTokenResponse.code() == successResponseCode) {
                UserSession.getInstance().authorization = refreshTokenResponse.body() //updating token
                UserSession.getInstance().saveAuthorizationData()

                // Every time flow is here, so new access token is obtained.
                // …
Run Code Online (Sandbox Code Playgroud)

android kotlin okhttp retrofit2 okhttp3

1
推荐指数
1
解决办法
861
查看次数

Okhttp websocket 发送消息以打开套接字

现在我有以下类,它使用 OkHttp 与 WebSockets 一起工作,但它的设置方式是我无法保持 WebSocket 打开,因此我可以向 Web 套接字发送新消息。如何在不创建新的 websocket 连接的情况下继续向同一个打开的 websocket 发送消息?

public class OkHttp extends WebSocketListener {
    public void run() {
        String hostname = "127.0.0.1";
        int port = 8888;
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port));

        OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).readTimeout(10, TimeUnit.SECONDS).build();

        Request request = new Request.Builder().url("ws://echo.websocket.org").build();
        client.newWebSocket(request, this);

        // Trigger shutdown of the dispatcher's executor so this process can exit
        // cleanly.
        client.dispatcher().executorService().shutdown();
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        webSocket.send("Hello...");
        webSocket.send("...World!");
        webSocket.send(ByteString.decodeHex("deadbeef"));
        webSocket.close(1000, …
Run Code Online (Sandbox Code Playgroud)

java okhttp okhttp3

1
推荐指数
1
解决办法
2616
查看次数

Okhttp 身份验证器 addHeader() 与 header()

在使用拦截器和身份验证器添加访问令牌标头时,当服务器以 401 响应时,我的身份验证器会被正确调用。

身份验证器通过单独的网络调用更新访问令牌,并将其设置在标头中以再次尝试。代码将与此示例非常相似

我只花了一个小时搞清楚我用错误的方法来再度令牌添加到认证,addHeaderVSheader

作品:

if (accessToken != null){
   // retry the failed 401 request with new access token
   return response.request().newBuilder()
                            .header("Authorization", accessToken) // use the new access token
                            .build();
}
Run Code Online (Sandbox Code Playgroud)

不起作用:

if (accessToken != null){
   // retry the failed 401 request with new access token
   return response.request().newBuilder()
                            .addHeader("Authorization", accessToken) // use the new access token
                            .build();
}
Run Code Online (Sandbox Code Playgroud)

这里会发生什么,为什么addHeader()行为与header()

android restful-authentication okhttp retrofit2

1
推荐指数
1
解决办法
407
查看次数