本文整理了Java中com.squareup.okhttp.Call
类的一些代码示例,展示了Call
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Call
类的具体详情如下:
包路径:com.squareup.okhttp.Call
类名称:Call
暂无
代码示例来源:origin: TommyLemon/APIJSON
/**
* @param client
* @param request
* @return
* @throws Exception
*/
private String getResponseJson(OkHttpClient client, Request request) throws Exception {
if (client == null || request == null) {
Log.e(TAG, "getResponseJson client == null || request == null >> return null;");
return null;
}
Response response = client.newCall(request).execute();
return response.isSuccessful() ? response.body().string() : null;
}
代码示例来源:origin: xinghongfei/LookLook
private void deliveryResult(final ResultCallback callback, Request request) {
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, final IOException e) {
sendFailCallback(callback, e);
}
@Override
public void onResponse(Response response) throws IOException {
try {
String str = response.body().string();
if (callback.mType == String.class) {
sendSuccessCallBack(callback, str);
} else {
Object object = JsonUtils.deserialize(str, callback.mType);
sendSuccessCallBack(callback, object);
}
} catch (final Exception e) {
sendFailCallback(callback, e);
}
}
});
}
代码示例来源:origin: wangdan/AisenWeiBo
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
// 停止网络请求,如果不为空
try {
if (mCall != null) {
mCall.cancel();
}
} catch (Throwable e) {
}
return super.cancel(mayInterruptIfRunning);
}
代码示例来源:origin: nostra13/Android-Universal-Image-Loader
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
Request request = new Request.Builder().url(imageUri).build();
ResponseBody responseBody = client.newCall(request).execute().body();
InputStream inputStream = responseBody.byteStream();
int contentLength = (int) responseBody.contentLength();
return new ContentLengthInputStream(inputStream, contentLength);
}
}
代码示例来源:origin: aa112901/remusic
public static String getResposeString(String action1) {
try {
mOkHttpClient.setConnectTimeout(1000, TimeUnit.MINUTES);
mOkHttpClient.setReadTimeout(1000, TimeUnit.MINUTES);
Request request = new Request.Builder()
.url(action1)
.build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
String c = response.body().string();
Log.e("billboard", c);
return c;
}
} catch (Exception e) {
e.printStackTrace();
}
// mOkHttpClient.setCookieHandler(new CookieManager(
// new PersistentCookieStore(getContext().getApplicationContext()),
// CookiePolicy.ACCEPT_ALL));
return null;
}
代码示例来源:origin: aa112901/remusic
public static Bitmap getBitmapStream(Context context, String url, boolean forceCache) {
try {
File sdcache = context.getExternalCacheDir();
//File cacheFile = new File(context.getCacheDir(), "[缓存目录]");
Cache cache = new Cache(sdcache.getAbsoluteFile(), 1024 * 1024 * 30); //30Mb
mOkHttpClient.setCache(cache);
mOkHttpClient.setConnectTimeout(1000, TimeUnit.MINUTES);
mOkHttpClient.setReadTimeout(1000, TimeUnit.MINUTES);
Request.Builder builder = new Request.Builder()
.url(url);
if (forceCache) {
builder.cacheControl(CacheControl.FORCE_CACHE);
}
Request request = builder.build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return _decodeBitmapFromStream(response.body().byteStream(), 160, 160);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
代码示例来源:origin: aa112901/remusic
public static void getOut(final String url) {
try {
mOkHttpClient.setConnectTimeout(1000, TimeUnit.MINUTES);
mOkHttpClient.setReadTimeout(1000, TimeUnit.MINUTES);
Request request = new Request.Builder()
.url(url)
.build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
FileOutputStream fo = new FileOutputStream("/storage/emulated/0/" + "gedangein" + ".json");
byte[] c = new byte[1024];
while (response.body().source().read(c) != -1) {
fo.write(c);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
代码示例来源:origin: commonsguy/cw-omnibus
@Override
public void run() {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(SO_URL).build();
Response response=client.newCall(request).execute();
if (response.isSuccessful()) {
Reader in=response.body().charStream();
BufferedReader reader=new BufferedReader(in);
SOQuestions questions=
new Gson().fromJson(reader, SOQuestions.class);
reader.close();
EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
}
else {
Log.e(getClass().getSimpleName(), response.toString());
}
}
catch (Exception e) {
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
}
}
}
代码示例来源:origin: facebook/stetho
@Test
public void testWithResponseCompression() throws IOException {
ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);
byte[] uncompressedData = repeat(".", 1024).getBytes();
byte[] compressedData = compress(uncompressedData);
MockWebServer server = new MockWebServer();
server.start();
server.enqueue(new MockResponse()
.setBody(new Buffer().write(compressedData))
.addHeader("Content-Encoding: gzip"));
Request request = new Request.Builder()
.url(server.url("/"))
.build();
Response response = mClientWithInterceptor.newCall(request).execute();
// Verify that the final output and the caller both saw the uncompressed stream.
assertArrayEquals(uncompressedData, response.body().bytes());
assertArrayEquals(uncompressedData, capturedOutput.toByteArray());
// And verify that the StethoInterceptor was able to see both.
Mockito.verify(mMockEventReporter)
.dataReceived(
anyString(),
eq(compressedData.length),
eq(uncompressedData.length));
server.shutdown();
}
代码示例来源:origin: chentao0707/SimplifyReader
throws IOException, AuthFailureError {
OkHttpClient client = mClient.clone();
int timeoutMs = request.getTimeoutMs();
client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);
Call okHttpCall = client.newCall(okHttpRequest);
Response okHttpResponse = okHttpCall.execute();
StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message());
BasicHttpResponse response = new BasicHttpResponse(responseStatus);
response.setEntity(entityFromOkHttpResponse(okHttpResponse));
代码示例来源:origin: BolexLiu/AutoEx
public static void dogetHttp3(final String urls, final HResponse mHResponse) {
try {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(60, TimeUnit.SECONDS);
Request build1 = new Request.Builder().url(urls).get().build();
Response execute = client.newCall(build1).execute();
if (execute == null || execute.body() == null) {
mHResponse.onError("没有找到任何可参考的,真可惜。");
return;
}
String string = execute.body().string();
mHResponse.onFinish(string);
} catch (IOException e) {
e.printStackTrace();
mHResponse.onError(e.getMessage());
}
}
}
代码示例来源:origin: wangdan/AisenWeiBo
mCall = httpClient.newCall(request);
Response response = mCall.execute();
if (response == null) {
throw new TaskException(TaskException.TaskError.failIOError.toString());
int statusCode = response.code();
if (!(statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_PARTIAL)) {
throw new TaskException(TaskException.TaskError.failIOError.toString());
String encoding = response.header("Content-Encoding");
if (encoding != null && !TextUtils.isEmpty(encoding) &&
"gzip".equals(encoding)) {
imageStream = new GZIPInputStream(response.body().byteStream());
Logger.w(TAG, "解压gzip文件, 解压前大小:");
} else {
imageStream = response.body().byteStream();
total = response.body().contentLength();
} catch (Exception e) {
代码示例来源:origin: org.echocat.marquardt/client
/**
* {@inheritDoc}
*/
@Override
public boolean signOut(final Certificate<SIGNABLE> certificate) throws IOException {
final Request request = sendRequestWithCertificateHeader(_baseUri + "/auth/signOut", POST_METHOD, certificate);
final Response response = _addSignedHeaderHttpClient.newCall(request).execute();
if (response.code() != NO_CONTENT_STATUS) {
throw ResponseStatusTranslation.from(response.code()).translateToException(response.message());
}
return true;
}
代码示例来源:origin: io.macgyver/macgyver-core
public List<X509Certificate> fetchCertificates(String httpUrl)
throws IOException {
OkHttpClient c = new OkHttpClient();
CertExtractor extractor = new CertExtractor();
c.setHostnameVerifier(extractor);
c.setSslSocketFactory(SslTrust.withoutCertificateValidation()
.getSocketFactory());
Request r = new Request.Builder().url(httpUrl).build();
Response response = c.newCall(r).execute();
response.body().close();
return extractor.certList;
}
代码示例来源:origin: com.dropbox.core/dropbox-core-sdk
@Override
public Response doGet(String url, Iterable<Header> headers) throws IOException {
Request.Builder builder = new Request.Builder().get().url(url);
toOkHttpHeaders(headers, builder);
configureRequest(builder);
com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
response = interceptResponse(response);
Map<String, List<String>> responseHeaders = fromOkHttpHeaders(response.headers());
return new Response(response.code(), response.body().byteStream(), responseHeaders);
}
代码示例来源:origin: commonsguy/cw-omnibus
@Override
public void onHandleWork(@NonNull Intent i) {
Request request=new Request.Builder()
.url(i.getData().toString())
.build();
try {
Response response=
BackupService.OKHTTP_CLIENT.newCall(request).execute();
File toRestore=new File(getCacheDir(), "backup.zip");
if (toRestore.exists()) {
toRestore.delete();
}
BufferedSink sink = Okio.buffer(Okio.sink(toRestore));
sink.writeAll(response.body().source());
sink.close();
ZipUtils.unzip(toRestore, getFilesDir(),
BackupService.ZIP_PREFIX_FILES);
ZipUtils.unzip(toRestore,
BackupService.getSharedPrefsDir(this),
BackupService.ZIP_PREFIX_PREFS);
ZipUtils.unzip(toRestore, getExternalFilesDir(null),
BackupService.ZIP_PREFIX_EXTERNAL);
EventBus.getDefault().post(new RestoreCompletedEvent());
}
catch (Exception e) {
Log.e(getClass().getSimpleName(),
"Exception restoring backup", e);
EventBus.getDefault().post(new RestoreFailedEvent());
}
}
代码示例来源:origin: commonsguy/cw-omnibus
.post(RequestBody.create(JSON, "{}"))
.build();
Response response=OKHTTP_CLIENT.newCall(request).execute();
if (response.code()==201) {
String backupURL=response.header("Location");
.put(RequestBody.create(ZIP, backup))
.build();
response=OKHTTP_CLIENT.newCall(request).execute();
if (response.code()==201) {
String datasetURL=response.header("Location");
SharedPreferences prefs=
代码示例来源:origin: survivingwithandroid/Surviving-with-android
OkHttpClient client = new OkHttpClient();
Request req = new Request.Builder().addHeader("X-Auth-Token", apiKey)
.url("http://things.ubidots.com/api/v1.6/variables/" + varId + "/values")
.build();
client.newCall(req).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
代码示例来源:origin: spotify/apollo
&& client.getReadTimeout() != apolloRequest.ttl().get().toMillis()) {
finalClient = client.clone();
finalClient.setReadTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS);
finalClient.newCall(request).enqueue(TransformingCallback.create(result));
代码示例来源:origin: licheedev/Custom-Glide-ModelLoader-Demo
private InputStream fetchStream(String url) {
// 缓存请求,用来及时取消连接
mFetchStreamCall = syncGet(url);
try {
return mFetchStreamCall.execute().body().byteStream();
} catch (IOException e) {
//e.printStackTrace();
}
return null;
}
内容来源于网络,如有侵权,请联系作者删除!