我需要知道如何在改造中添加授权cookie头.我已经看过使用请求截取等的建议.以下是我正在尝试的,但这是正确的吗?首先,我已经需要一个RequestAdatper来第一次获取会话ID.这只能由请求适配器的构建器设置.但我需要提出一个请求才能获得会话ID.我需要两个休息适配器,一个用于获取sessionId,另一个用于获取它之后.我真正需要的是一个适配器上的方法,在我得到它之后设置cookie,但它似乎不是这样的方法.这变得很尴尬.如何在改造中设置授权cookie?我在常见问题解答或教程中没有看到这一点.
RequestInterceptor requestInterceptor = new RequestInterceptor()
{
@Override
public void intercept(RequestFacade request) {
request.addHeader("Set-Cookie", "sessionId="+sessionIdentifier);
}
};
RestAdapter.Builder().setServer(serverURL)..setRequestIntercepter(requestIntercepter).build();
// but I don't have sessionId when this is first issued ???
Run Code Online (Sandbox Code Playgroud) 我已经使用OkHttp库进行了一些性能测试,发现它很棒.它向http://httpbin.org/delay/1提出了80个请求,它在我的HTC One手机上的4.7秒内故意暂停每个请求1秒.我查看了代码,我试图找出它为什么这么快.开发人员(Square Inc)宣传连接池和异步调用,我认为这两者都有助于提高性能.
我来自.NET世界,在.NET 4.5中,您有一个真正的异步HTTP库和Async GetResponse方法.通过在等待响应时将线程交给操作系统,您可以释放资源以启动更多HTTP请求或其他内容.问题是我看不到与OkHttp相同的模式(或者我已经研究过的任何其他Android库).那么我怎么能在4秒内执行80个1秒的请求呢?它不是基于线程的,对吧?我没有开出80(或20)个线程?
具体来说,在com.squareup.okhttp.Call.beginRequest()中,我看到并没有让sendRequest和getResponse调用之间产生线程:
if (canceled) return null;
try {
engine.sendRequest();
if (request.body() != null) {
BufferedSink sink = engine.getBufferedRequestBody();
request.body().writeTo(sink);
}
engine.readResponse();
} catch (IOException e) {
HttpEngine retryEngine = engine.recover(e, null);
if (retryEngine != null) {
engine = retryEngine;
continue;
}
// Give up; recovery is not possible.
throw e;
}
Response response = engine.getResponse();
Run Code Online (Sandbox Code Playgroud)
那么,如何才能实现80个"并行"呼叫?
我不需要知道这个以便使用库,但异步编程让我感兴趣,我真的很想了解OkHttp/SquareInc是如何解决这个问题的.
我想问一下如何在java中使用okhttpclient下载图像文件,因为我需要下载带有会话的文件这里是正式给出的代码,但我不知道如何使用它作为图像文件下载
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用HTTPS与自签名证书的连接.
我按照这里提到的创建自签名证书的步骤 - 创建自签名证书.
即使在浏览器中一切正常,它只向我显示我的证书由未知CA签名的消息.
但是我的证书中的FQDN(服务器名称不匹配)名称有问题,因为我在生成证书时设置了错误的名称.
我已经重新生成它,现在没有这样的错误.
我需要从移动Android客户端使用我的服务器sertificate,我找到了关于此问题的精彩文章 - 在Android中使用自签名或未知SSL证书的Retrofit.我已经遵循了所有步骤,但遗憾的是得到了一个错误(例外).
javax.net.ssl.SSLPeerUnverifiedException: Hostname 195.xx.xx.xx not verified:
certificate: sha1/qvH7lFeijE/ZXxNHI0B/M+AU/aA=
DN: 1.2.840.113549.1.9.1=#160e63726f73704078616b65702e7275,CN=195.xx.xx.xx,OU=Departament of Development,O=CROSP Solutions,L=Chernihiv,ST=Chernihiv,C=UA
subjectAltNames: []
at com.squareup.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:124)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的主机名相同,但仍然存在错误.
请帮忙处理这个问题,我将不胜感激任何帮助.
谢谢.
伪解决方案
当然我之前搜索过并找到了HostName Verifier Solution.
我试过了,它有效.但是可以使用这种解决方法,我将证书添加到我的应用程序中,以便像在前面的示例中一样动态地读取它,它是否仍然在这种情况下使用.
OkHttp的解决方案是一行.(如果您按照教程中的所有步骤操作).
okHttpClient.setHostnameVerifier(new NullHostNameVerifier());
Run Code Online (Sandbox Code Playgroud)
但我还是觉得这不是最好的解决方案,请问有什么想法吗?
场景:我使用OkHttp/Retrofit访问Web服务:同时发送多个HTTP请求.在某些时候,身份验证令牌到期,并且多个请求将获得401响应.
问题:在我的第一个实现中,我使用拦截器(这里简化),每个线程都尝试刷新令牌.这导致一团糟.
public class SignedRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// 1. sign this request
request = request.newBuilder()
.header(AUTH_HEADER_KEY, BEARER_HEADER_VALUE + token)
.build();
// 2. proceed with the request
Response response = chain.proceed(request);
// 3. check the response: have we got a 401?
if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
// ... try to refresh the token
newToken = mAuthService.refreshAccessToken(..);
// sign the request with the new token and proceed …Run Code Online (Sandbox Code Playgroud) 我正在使用改造来提出请求.
我有以下错误:
java.net.ProtocolException:后续请求太多:21
代码如下:
private OkHttpClient httpClient;
private CookieManager cookieManager;
public <S> S createCookieService(Class<S> serviceClass) {
httpClient.interceptors().clear();
httpClient.setCookieHandler(cookieManager);
Retrofit.Builder builder = new Retrofit
.Builder()
.client(httpClient)
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
Run Code Online (Sandbox Code Playgroud)
然后我提出要求:
例:
1)登录
@POST("/login")
Call<User> login();
Run Code Online (Sandbox Code Playgroud)
2)一些要求:
@GET("/request")
Call<PojoPojo> getPojo();
Run Code Online (Sandbox Code Playgroud)
我收到这个错误的后续请求太多:21.
请帮忙.
我在我的OkHttp客户端上放了以下拦截器:
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
Log.d("Response", response.body().string());
return response;
}
});
Run Code Online (Sandbox Code Playgroud)
但是,这对于Retrofit 2来说并不是很好.看起来你只能从响应中读取一次流,这可能是造成异常的原因.我在想改造试图解析日志已经解析过的流.那我如何得到回应呢?我正在尝试调试一个非常讨厌和奇怪的格式错误的json异常.
这是异常堆栈跟踪:
07 - 28 10: 58: 21.575 22401 - 22529 / REDACTED E / AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: REDACTED, PID: 22401
java.lang.IllegalStateException: closed
at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java: 378)
at okio.Buffer.writeAll(Buffer.java: 956)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java: 92)
at okhttp3.ResponseBody.bytes(ResponseBody.java: 83)
at okhttp3.ResponseBody.string(ResponseBody.java: 109)
at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 90)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
at …Run Code Online (Sandbox Code Playgroud) 这需要花费很多时间来获取数据json.当删除并再次安装它将json在1分钟内得到,当我再次点击按钮,json它需要这么多时间,仍然数据没有进入listview
这是我的异常代码
E/JSONDemo: IOExceptiojava.net.SocketTimeoutException
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:493)
at java.net.PlainSocketImpl.-wrap0(PlainSocketImpl.java)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:242)
at okio.Okio$2.read(Okio.java:140)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:238)
at okio.RealBufferedSource.indexOf(RealBufferedSource.java:325)
at okio.RealBufferedSource.indexOf(RealBufferedSource.java:314)
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:210)
at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:184)
at okhttp3.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:125)
at okhttp3.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:775)
at okhttp3.internal.http.HttpEngine.access$200(HttpEngine.java:86)
at okhttp3.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:760)
at okhttp3.internal.http.HttpEngine.readResponse(HttpEngine.java:613)
at okhttp3.RealCall.getResponse(RealCall.java:244)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.access$100(RealCall.java:30)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Run Code Online (Sandbox Code Playgroud)
这是java文件中的json代码:
progress = ProgressDialog.show(MainActivity.this, "dialog title", "dialog message", true);
Toast.makeText(MainActivity.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = "ConstantValue.URL";
RequestBody formBody = new …Run Code Online (Sandbox Code Playgroud) 使用Retrofit 1.6.0,OkHTTP 2.0.0和OkHTTP-UrlConnection 2.0.0.
我正在使用Retrofit对不存在的URL进行服务POST.正如预期的那样调用失败回调.但是,RetrofitError参数没有响应.我真的想抓住使用返回的HTTP状态代码
error.getResponse().getStatus()
Run Code Online (Sandbox Code Playgroud)
但由于getResponse()返回null,我不能.
为什么getResponse()为null,如何获取状态?
谢谢.
另外,我收到的错误是UnknownHostException,正如预期的那样.重复:我期待这个错误.我想知道如何获取HTTP状态代码或者为什么error.getResponse()返回null.
编辑:这是一些代码:
RestAdapterBuilderClass.java
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://badURL.DoesntMatter/");
.setRequestInterceptor(sRequestInterceptor)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
sService = restAdapter.create(ServiceInterface.class);
ServiceInterface.java
@POST("/Login")
void login(@Body JsonObject body, Callback<String> callback);
CallbackClass.java
@Override
public void failure(RetrofitError error) {
if (error.getResponse() == null) {
// error.getResponse() is null when I need to get the status code
// from it.
return;
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用改造2和OkHttp3从服务器请求数据.我刚刚添加了一个离线缓存代码,但它没有按预期工作.我收到错误"无法解析主机"<>":没有与主机名关联的地址."
当它试图从缓存中获取检索数据时(没有互联网连接时)会发生这种情况.下面是一段代码片段.
public static Interceptor provideCacheInterceptor() {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// re-write response header to force use of cache
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(2, TimeUnit.MINUTES)
.build();
return response.newBuilder()
.header(CACHE_CONTROL, cacheControl.toString())
.build();
}
};
}
public static Interceptor provideOfflineCacheInterceptor() {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!hasNetwork) {
CacheControl cacheControl = new CacheControl.Builder()
.onlyIfCached()
.maxStale(7, TimeUnit.DAYS) …Run Code Online (Sandbox Code Playgroud)