java - Curl 到 okhttp 转换

标签 java android retrofit okhttp

我有一个形式的 curl curl -v -u username:password -H "Content-Type: application/json"........

无法破解如何让 -u 部分工作。尝试过多种选择,例如

Authenticator proxyAuthenticator = new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                String credential = Credentials.basic("username", "password");
                return response.request().newBuilder()
                        .addHeader("Proxy-Authorization", credential)
                        .addHeader("Content-Type", "application/json")
                        .build();
            }
        };

httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                RequestBody requestBody = new FormBody.Builder().add("username", "password").build();
                Request request = original.newBuilder()
                        .addHeader("Content-Type", "application/json")
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }
        });

这两个都不起作用。即使将其发布为标题也无法使其正常工作。请大家帮忙!

最佳答案

按照这个解决了。

protected Authenticator getBasicAuth(final String username, final String password) {
        return new Authenticator() {
            private int mCounter = 0;

            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                if (mCounter++ > 0) {
                    return null;
                } else {
                    String credential = Credentials.basic(username, password);
                    return response.request().newBuilder().header("Authorization", credential).build();
                }
            }
        };
    }

然后将其作为身份 validator 添加到我的客户端。

关于java - Curl 到 okhttp 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50638803/

相关文章:

java - 在 Android 上将改造响应解析为包含自定义对象的自定义对象

安卓-java.io.IOException : Canceled when disposed

android - 如何在 WebView 中显示方向

android - 错误 : No Retrofit annotation found.(参数 #2)

java - Spring数据的增量mapreduce

java - 如何在不使用 foreach 的情况下合并两个列表?

JAVA:如何使用具有相同目标命名空间的多个模式的 xerces SAXParser

java - 在子接口(interface)中声明具有相同声明的通用方法的体系结构重要性是什么

android - ViewModels + Hilt : cannot inline bytecode built with JVM target 1. 8 到正在使用 JVM 目标 1.6 构建的字节码

android - 获取实际的 View 高度