我需要从我的api中检索需要标头身份验证的图像.我正在为毕加索指定一个自定义下载程序,但图像永远不会显示.我是否正确覆盖了openConnection方法?
Picasso.Builder builder = new Picasso.Builder(getApplicationContext());
builder.downloader(new OkHttpDownloader(getApplicationContext()) {
@Override
protected HttpURLConnection openConnection(Uri uri) throws IOException {
HttpURLConnection connection = super.openConnection(uri);
connection.setRequestMethod("GET");
connection.setRequestProperty("X_AUTH_TOKEN", authToken);
return connection;
}
});
Picasso picasso = builder.build();
picasso.with(getApplicationContext()).load("http://example.com/api/users/pic/14").into(ivProfilePic);
Run Code Online (Sandbox Code Playgroud) 我想将okhttp源代码(不是jar)作为模块导入android studio.有什么建议吗?谢谢 !
我需要使用所有请求参数生成签名验证:
所以,我写了一个小的SignatureInterceptor类:
public class SignatureInterceptor implements Interceptor {
private String token;
private String signature = "";
private String method;
private String query;
public SignatureInterceptor() {
this.token = "456456456456";
}
@Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
method = originalRequest.method();
query = originalRequest.urlString();
Request authenticatedRequest = originalRequest.newBuilder()
.method(originalRequest.method(), authenticate(originalRequest.body()))
.addHeader("signature", signature)
.build();
return chain.proceed(authenticatedRequest);
}
private RequestBody authenticate(final RequestBody body) …Run Code Online (Sandbox Code Playgroud) 我OkHttp第一次使用.我看到教程说如果想要使用Response Caching,我必须调用new OkHttpClient() 一次(单例实例).OkhttpClient通过synchronized方法是线程安全的.但是在我的应用程序中,有许多线程连接到网络以同时获取远程数据,一些线程必须等待线程完成获取数据才能执行其操作.
那么它的表现不是比平时好吗?
如果是,如果我没有启用Reponse Caching,我应该new OkHttpClient() 多次拨打电话以获得更好的性能吗?
谢谢
我正在尝试将okHttp与Web服务连接,但使用不同的端口,例如10000.我的想法是在单元测试期间使用代理存根响应.但是,没有足够的文档来使用这个库.事实上,我的实施是:
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(TIMEOUT_MS, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)
例如,对于其他库,例如loopj,此功能是可能的:
httpClient.setProxy("localhost", 10000);
Run Code Online (Sandbox Code Playgroud)
我正在使用这个版本: com.squareup.okhttp:okhttp:2.5.0
我正在做一些REST调用,并获得响应.有时,响应不会正常,所以我需要解析响应,并以适当的方式呈现它以供用户注意并做出反应.我有这个代码:
if(response.code()!=200){
JSONArray jsonError=null;
try {
Log.i("David", "Incorrect response: "+response.errorBody().string());
jsonError = new JSONArray(response.errorBody().string());//After this line, jsonError is null
JSONObject message=jsonError.getJSONObject(0);
String errorJson=message.getString("message");
Log.i("David", "Error received: "+errorJson);
AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity());
dialog.setTitle(getString(R.string.error));
dialog.setMessage(getString(R.string.errorfound) + errorJson);
dialog.setPositiveButton(getString(R.string.aceptar), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
这样,日志行"错误响应"显示完美,包含错误代码,消息等.这是收到的JSON:
[{"coderror":"-2","gravedad":"1","message":"Device imei 34543564768463435345 not logged in","cause":""}]
Run Code Online (Sandbox Code Playgroud)
我的问题是,正如我所说,日志记录工作正常,但是当我尝试将JSON转换为JsonArray时......它失败了.在下一行中,JsonError对象变为null.
为什么我不能解析回复?谢谢.
我目前正在编写一个需要结合api调用的应用程序,因此第一次使用rxjava,因为它似乎更方便处理异步事件和Android生命周期.
但是,应用程序有时还需要加载打包在zip存档中的静态数据集.我尝试使用rx进行此操作以及一致性并且它运行良好,但我真的没有掌握如何订阅progress-events以使用文件下载进度更新UI.
这是我现在使用的代码,用于下载使用okhttp-library的文件:
downloadService.downloadFile(filename)
.flatMap(new Func1<Response<ResponseBody>, Observable<File>>()
{
@Override
public Observable<File> call(final Response<ResponseBody> responseBodyResponse)
{
return Observable.create(new Observable.OnSubscribe<File>()
{
@Override
public void call(Subscriber<? super File> subscriber)
{
try
{
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), filename);
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(responseBodyResponse.body().source());
sink.close();
subscriber.onNext(file);
subscriber.onCompleted();
}
catch (IOException e)
{
e.printStackTrace();
subscriber.onError(e);
}
}
});
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<File>()
{
@Override
public void onCompleted()
{
Log.d("downloadZipFile", "onCompleted");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
Log.d("downloadZipFile", "Error " + e.getMessage()); …Run Code Online (Sandbox Code Playgroud) 每当我在此站点上执行OKHttp Post请求时,响应代码为302,响应主体为:
<html>
<head>
<title>Object moved</title>
</head>
<body>
<h2>Object moved to <a href="/GradebookSummary.aspx">here</a>.
</h2>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
OkHttpClient client = new OkHttpClient().newBuilder()
.followRedirects(false)
.followSslRedirects(false)
.build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "checkCookiesEnabled=true&checkMobileDevice=false&checkStandaloneMode=false&checkTabletDevice=false&portalAccountUsername=username&portalAccountPassword=password");
Request request = new Request.Builder()
.url("https://hac.chicousd.org/LoginParent.aspx?page=GradebookSummary.aspx")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何处理回复才能转到新位置?
在我们的Android应用程序中,我正在向我们的(NGINX)服务器发送相当大的文件,所以我希望使用gzip作为我的Retrofit POST消息.
有许多关于OkHttp的文档透明地使用gzip或更改头文件以接受gzip(即在GET消息中).
但是如何启用此功能以从我的设备发送gzip http POST消息?我是否必须写一个自定义的Intercepter或其他东西?或者只是在标题中添加一些东西?
我当前使用的是okhttp 3.10.0,最近我发现为每个新请求创建一个新客户端对每个拥有自己的连接池的客户端都是不利的。
我在servlet中使用okhttp。我现在要做的就是在每个Servlet中声明一个静态客户端,并在init()方法中对其进行初始化。
client = new OkHttpClient.Builder()
.readTimeout(15000,TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(false)
.connectTimeOut(10000,TimeUnit.MILLISECONDS)
.connectionPool(new ConnectionPool(20,5L,TimeUnit.MINUTES)
.build();
Run Code Online (Sandbox Code Playgroud)
现在,这里是最大空闲连接的配置,我将其设置为20,空闲超时设置为5分钟。
1)实际的池大小是多少,即该池将具有的最大连接数(通过代码查看,我发现它可能是Integer.MAX_VALUE,与主机的最大同时连接数默认为64,但我不确定) ?
2)这种方法足够好吗?我当前的方法是使每个servlet一个客户端。所以我应该改为有一个单例类,该类为所有Servlet提供相同的客户端,在这种情况下,我应该为以下规范配置理想的负载吗?我找不到如何配置实际池大小,所以我不知道如果可能的话
数字海洋飞沫
公羊2GB
CPU核心2
Tomcat最大堆768mb
Nginx并发工人1000
MySQL的最大内存〜800mb
负载我想每秒最多支持500个用户