标签: okhttp

Okhttp响应主线程上的回调

我创建了一个帮助程序类来处理我的应用程序中的所有http调用.它是okhttp的一个简单的单例包装器,看起来像这样(我省略了一些不重要的部分):

public class HttpUtil {

    private OkHttpClient client;
    private Request.Builder builder;

    ...

    public void get(String url, HttpCallback cb) {
        call("GET", url, cb);
    }

    public void post(String url, HttpCallback cb) {
        call("POST", url, cb);
    }

    private void call(String method, String url, final HttpCallback cb) {
        Request request = builder.url(url).method(method, method.equals("GET") ? null : new RequestBody() {
            // don't care much about request body
            @Override
            public MediaType contentType() {
                return null;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {

            }
        }).build(); …
Run Code Online (Sandbox Code Playgroud)

multithreading android okhttp

61
推荐指数
3
解决办法
4万
查看次数

OkHttp如何记录请求体

我正在使用一个拦截器,我想记录我正在制作的请求的正文,但我看不到这样做的任何方法.

可能吗 ?

public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();

        double time = (t2 - t1) / 1e6d;

        if (request.method().equals("GET")) {
            Logs.info(String.format("GET " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), response.code(), response.headers(), response.body().charStream()));
        } else if (request.method().equals("POST")) {
            Logs.info(String.format("POST " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body(), response.code(), response.headers(), response.body().charStream()));
        } else if (request.method().equals("PUT")) {
            Logs.info(String.format("PUT …
Run Code Online (Sandbox Code Playgroud)

android okhttp

61
推荐指数
5
解决办法
4万
查看次数

OkHttp Post Body as JSON

所以,当我使用Koush的Ion时,我能够通过一个简单的方式在我的帖子中添加一个json体 .setJsonObjectBody(json).asJsonObject()

我正在转向OkHttp,我真的没有看到一个很好的方法来做到这一点.我到处都收到错误400.

有人有主意吗?

我甚至尝试将其手动格式化为json字符串.

String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);

String url = mBaseUrl + "/" + id + "/report";

Request request = new Request.Builder()
        .header("X-Client-Type", "Android")
        .url(url)
        .post(RequestBody
                .create(MediaType
                    .parse("application/json"),
                        "{\"Reason\": \"" + reason + "\"}"
                ))
        .build();

client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
    @Override
    public void onFailure(Request request, IOException throwable) {
        throwable.printStackTrace();
    }

    @Override
    public void onResponse(Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException(
                "Unexpected code " + response);
        runOnUiThread(new Runnable() {
            @Override …
Run Code Online (Sandbox Code Playgroud)

android json http-post android-ion okhttp

60
推荐指数
4
解决办法
9万
查看次数

如何使用OkHttp/Retrofit重试HTTP请求?

我在我的Android项目中使用Retrofit/OkHttp(1.6).

我没有找到内置于其中任何一个的任何请求重试机制.在搜索更多时,我看到OkHttp似乎有沉默重试.我没有看到我的任何连接(HTTP或HTTPS)发生这种情况.如何使用okclient配置重试?

现在,我正在捕获异常并重试维护计数器变量.

android retrofit okhttp

59
推荐指数
4
解决办法
6万
查看次数

无法获得OkHttp的response.body.toString()来返回一个字符串

我正在尝试使用OkHttp获取一些json数据,并且无法弄清楚为什么当我尝试记录response.body().toString()我得到的是Results:? com.squareup.okhttp.Call$RealResponseBody@41c16aa8

try {
        URL url = new URL(BaseUrl);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .header(/****/)
                .build();

        Call call = client.newCall(request);
        Response response = call.execute();

        **//for some reason this successfully prints out the response**
        System.out.println("YEAH: " + response.body().string());

        if(!response.isSuccessful()) {
            Log.i("Response code", " " + response.code());
        }

        Log.i("Response code", response.code() + " ");
        String results = response.body().toString();

        Log.i("OkHTTP Results: ", results);
Run Code Online (Sandbox Code Playgroud)

日志

我不知道我在这里做错了什么.我如何获得响应字符串?

java android okhttp

59
推荐指数
3
解决办法
6万
查看次数

CertPathValidatorException:找不到证书路径的信任锚 - Retrofit Android

我正在创建一个https用于与服务器通信的android应用程序.我正在使用retrofitOkHttp提出请求.这些适用于标准http请求.以下是我遵循的步骤.

步骤1: 使用该命令从服务器获取cert文件

echo -n | openssl s_client -connect api.****.tk:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > gtux.cert
Run Code Online (Sandbox Code Playgroud)

步骤2: 使用以下命令将证书转换为BKS格式

keytool -importcert -v -trustcacerts -file "gtux.cert" -alias imeto_alias -keystore "my_keystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "bcprov-jdk16-146.jar" -storetype BKS
Run Code Online (Sandbox Code Playgroud)

它问我密码并且文件已成功创建.

第3步:

创建一个OkHttpClient并使用它来发出https请求

public class MySSLTrust {
public static OkHttpClient trustcert(Context context){
    OkHttpClient okHttpClient = new OkHttpClient();
    try {
        KeyStore ksTrust = KeyStore.getInstance("BKS");
        InputStream instream = context.getResources().openRawResource(R.raw.my_keystore);
        ksTrust.load(instream, "secret".toCharArray());
        // TrustManager decides which certificate authorities to …
Run Code Online (Sandbox Code Playgroud)

ssl android retrofit okhttp

54
推荐指数
5
解决办法
9万
查看次数

不支持的操作:Android,Retrofit,OkHttp.在OkHttpClient中添加拦截器

我试图通过使用拦截器在Android中的Retrofit 2.0-beta3和OkHttpClient添加基于令牌的身份验证.但是当我在OkHttpClient中添加拦截器时,我得到UnsupportedOperationException.这是我的代码:在ApiClient.java中

public static TrequantApiInterface getClient(final String token) {
        if( sTreqantApiInterface == null) {

            Log.v(RETROFIT_LOG, "Creating api client for the first time");
            OkHttpClient okClient = new OkHttpClient();

            okClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();

                    // Request customization: add request headers
                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Authorization", token)
                            .method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });

            Retrofit client = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(okClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            sTreqantApiInterface = client.create(TrequantApiInterface.class);
        }
        return sTreqantApiInterface;
    } …
Run Code Online (Sandbox Code Playgroud)

java android retrofit okhttp retrofit2

54
推荐指数
2
解决办法
1万
查看次数

javax.net.ssl.SSLException:读取错误:ssl = 0x9524b800:系统调用期间的I/O错误,同级连接重置

在过去的几周里,我们的客户开始看到100个这样的"SSLException错误 - 连接重置连接",我无法弄清楚为什么

  1. 我们在okhttp上使用Retrofit,没有特殊配置

    public class OkHttpClientProvider implements IOkHttpClientProvider {
    
        OkHttpClient okHttpClient;
    
        public OkHttpClientProvider() {
            this.okHttpClient = createClient();
        }
    
        public OkHttpClient getOkHttpClient() {
            return this.okHttpClient;
        }
    
        private OkHttpClient createClient() {
            return new OkHttpClient();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

上述客户提供商是单身人士.RestAdapter是使用这个注入的客户端构建的(我们使用匕首) -

RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder()
                                        .setConverter(converter)
                                        .setEndpoint(networkRequestDetails.getServerUrl())
                                        .setClient(new OkClient(okHttpClientProvider.getOkHttpClient()))
                                        .setErrorHandler(new NetworkSynchronousErrorHandler(eventBus))
                                        );
Run Code Online (Sandbox Code Playgroud)

基于堆栈溢出解决方案,我发现了 -

  1. 服务器上的保持活动持续时间为180秒,OkHttp的默认值为300秒

  2. 服务器在其标头中返回"Connection:close",但客户端请求发送"Connection:keepAlive"

  3. 服务器支持TLS 1.0/1.1/1.2并使用Open SSL

  4. 我们的服务器最近已转移到另一个托管服务提供商的另一个地理位置,因此我不知道这些是否是DNS故障

  5. 我们尝试调整keepAlive之类的东西,在服务器上重新配置OpenSSL,但由于某种原因,Android客户端不断收到此错误

  6. 当您尝试使用应用程序发布内容或拉动刷新时,它会立即发生,并且不会出现任何延迟(在发生此异常之前,它甚至不会进入网络或延迟,这意味着连接已经断开).但尝试多次以某种方式"修复它",我们取得了成功.它会在以后再次发生

  7. 我们已经在服务器上使我们的DNS条目无效,看看这是否是由它引起的,但是没有帮助

  8. 它主要发生在LTE上,但我也在Wifi上看过它

我不想禁用keep alive,因为大多数现代客户都不这样做.此外,我们正在使用OkHttp 2.4,这是后冰淇淋三明治设备的一个问题,所以我希望它应该照顾这些潜在的网络问题.iOS客户端也获得了这些例外但接近100倍(iOS客户端使用AFNetworking 2.0).我正在努力寻找新的东西,在这一点上尝试,任何帮助/想法?

更新 - 通过okhttp添加完整堆栈跟踪

      retrofit.RetrofitError: Read error: ssl=0x9dd07200: I/O error during system call, Connection reset by …
Run Code Online (Sandbox Code Playgroud)

ssl android http retrofit okhttp

53
推荐指数
3
解决办法
7万
查看次数

Chrome DevTools 损坏 - Stetho 无法使用

Stetho 和 Google Chrome DevTools 在 macOS 更新后变得无法使用(我怀疑 macOS 更新是此错误的根源,但我更愿意提及它)。

这是在设备上打开“检查模式”后 DevTools 的外观(由 Facebook Stetho 库提供,适用于 Android 和 OKHttp)。

开发者工具窗口

页面上不再有“CSS”样式表,字体也发生了变化。许多标签页没有显示(即网络请求),我只能访问一些错误消息:

There were 84 bytes that were not consumed while processing request 4
There were 84 bytes that were not consumed while processing request 5
There were 84 bytes that were not consumed while processing request 6
Failed to clear temp storage: undefined
Run Code Online (Sandbox Code Playgroud)

我按照有关此问题的说明进行操作:无法清除临时存储和此问题:无法清除临时存储:Chrome 中的安全错误但我无法解决该问题。

这是我尝试过的:

  • 使用 AppCleaner 卸载并重新安装 Chrome
  • 从磁盘中删除 chrome 缓存
  • 从中删除 chrome 配置文件 ~/Library/Application\ …

android google-chrome google-chrome-devtools okhttp stetho

48
推荐指数
2
解决办法
5427
查看次数

OkHttp如何获得Json字符串?

解决方案:这是我的错误.

正确的方法是response.body().string()而不是response.body.toString()

我使用Jetty servlet,URL http://172.16.10.126:8789/test/path/jsonpage,每次请求此URL将返回

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
Run Code Online (Sandbox Code Playgroud)

它显示在将URL输入浏览器时,不幸的是,当我请求时,它显示的是除了json字符串之外的那种内存地址Okhttp.

TestActivity? com.squareup.okhttp.internal.http.RealResponseBody@537a7f84
Run Code Online (Sandbox Code Playgroud)

Okhttp代码我使用:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗?

java http embedded-jetty okhttp

47
推荐指数
4
解决办法
8万
查看次数