List of usage examples for com.squareup.okhttp Response code
int code
To view the source code for com.squareup.okhttp Response code.
Click Source Link
From source file:com.appstarter.utils.WebUtils.java
License:Apache License
public static String doHttpGet(String url) throws AppStarterException { if (BuildConfig.DEBUG) { Log.d(TAG, "doHttpGet - url: " + url); }//from w ww . jav a 2 s . c o m String ret = ""; OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout try { Request request = new Request.Builder().url(new URL(url)) // .header("User-Agent", "OkHttp Headers.java") // .addHeader("Accept", "application/json; q=0.5") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { String debugMessage = "doHttpGet - OkHttp.Response is not successful - " + response.message() + " (" + response.code() + ")"; throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage); } ret = response.body().string(); } catch (IOException e) { throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET); } return ret; }
From source file:com.appstarter.utils.WebUtils.java
License:Apache License
public static String doHttpPost(String url, List<NameValuePair> params) throws AppStarterException { if (BuildConfig.DEBUG) { Log.d(TAG, "doHttpPost - url: " + debugRequest(url, params)); }/*from w w w. j a v a 2s . c o m*/ String ret = ""; OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout FormEncodingBuilder builder = new FormEncodingBuilder(); for (NameValuePair nvp : params) { builder.add(nvp.getName(), nvp.getValue()); } RequestBody formBody = builder.build(); try { Request request = new Request.Builder().url(new URL(url)) // .header("User-Agent", "OkHttp Headers.java") // .addHeader("Accept", "application/json; q=0.5") .post(formBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { String debugMessage = "doHttpPost - OkHttp.Response is not successful - " + response.message() + " (" + response.code() + ")"; throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage); } ret = response.body().string(); } catch (IOException e) { throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET); } return ret; }
From source file:com.ariadnext.idcheckio.invoker.ApiClient.java
License:Apache License
/** * Handle the given response, return the deserialized object when the response is successful. * * @param <T> Type//www . ja va 2 s . c o m * @param response Response * @param returnType Return type * @throws ApiException If the response has a unsuccessful status code or * fail to deserialize the response body * @return Type */ public <T> T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful() || response.code() == 303) { if (returnType == null || response.code() == 204) { // returning null if the returnType is not defined, // or the status code is 204 (No Content) return null; } else { return deserialize(response, returnType); } } else { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } }
From source file:com.auth0.api.internal.ApplicationInfoRequest.java
License:Open Source License
@Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { String message = "Received app info failed response with code " + response.code() + " and body " + response.body().string(); postOnFailure(new IOException(message)); return;/*from ww w . j a v a 2s .co m*/ } try { String json = response.body().string(); JSONTokener tokenizer = new JSONTokener(json); tokenizer.skipPast("Auth0.setClient("); if (!tokenizer.more()) { postOnFailure(tokenizer.syntaxError("Invalid App Info JSONP")); return; } Object nextValue = tokenizer.nextValue(); if (!(nextValue instanceof JSONObject)) { tokenizer.back(); postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info")); } JSONObject jsonObject = (JSONObject) nextValue; Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject); Application app = getReader().readValue(jsonObject.toString()); postOnSuccess(app); } catch (JSONException | IOException e) { postOnFailure(new APIClientException("Failed to parse JSONP", e)); } }
From source file:com.auth0.api.internal.SimpleRequest.java
License:Open Source License
@Override public void onResponse(Response response) throws IOException { Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { Throwable throwable;//w w w .j av a 2s . c om try { Map<String, Object> payload = errorReader.readValue(byteStream); throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); } catch (IOException e) { throwable = new APIClientException("Request failed", response.code(), null); } postOnFailure(throwable); return; } try { Log.d(TAG, "Received successful response from " + response.request().urlString()); T payload = getReader().readValue(byteStream); postOnSuccess(payload); } catch (IOException e) { postOnFailure(new APIClientException("Request failed", response.code(), null)); } }
From source file:com.auth0.api.internal.VoidRequest.java
License:Open Source License
@Override public void onResponse(Response response) throws IOException { Log.d(TAG, String.format("Received response from request to %s with status code %d", response.request().urlString(), response.code())); final InputStream byteStream = response.body().byteStream(); if (!response.isSuccessful()) { Throwable throwable;// w w w . j a va 2s .c o m try { Map<String, Object> payload = errorReader.readValue(byteStream); throwable = new APIClientException("Request failed with response " + payload, response.code(), payload); } catch (IOException e) { throwable = new APIClientException("Request failed", response.code(), null); } postOnFailure(throwable); return; } postOnSuccess(null); }
From source file:com.auth0.request.internal.BaseRequest.java
License:Open Source License
protected APIException parseUnsuccessfulResponse(Response response) { try {//from w w w . ja v a 2s .c om final InputStream byteStream = response.body().byteStream(); Map<String, Object> payload = errorReader.readValue(byteStream); return new APIException("Request to " + url + " failed with response " + payload, response.code(), payload); } catch (Exception e) { return new APIException("Request to " + url + " failed", response.code(), null); } }
From source file:com.ayuget.redface.network.HTTPRedirection.java
License:Apache License
/** * Resolves a redirected URL {@code originalUrl} to its final location. * * If the URL is not really redirected, the original URL is returned. *//*from ww w .j a v a 2 s . c o m*/ public static Observable<String> resolve(final String originalUrl) { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { OkHttpClient httpClient = new OkHttpClient(); httpClient.setFollowRedirects(false); Request request = new Request.Builder().url(originalUrl).build(); try { Response response = httpClient.newCall(request).execute(); if (response.code() == REDIRECTED_STATUS_CODE) { String locationHeader = response.header(LOCATION_HEADER); String targetUrl = locationHeader == null ? originalUrl : "http://" + new URL(originalUrl).getHost() + locationHeader; Timber.d("URL '%s' is redirected to '%s'", originalUrl, targetUrl); subscriber.onNext(targetUrl); } else { Timber.w("URL '%s' is not redirected", originalUrl); subscriber.onNext(originalUrl); } } catch (IOException e) { subscriber.onError(e); } } }); }
From source file:com.baasbox.android.net.OkClient.java
License:Apache License
@Override public HttpResponse execute(HttpRequest request) throws BaasException { String contentType = request.headers.get("Content-Type"); Request.Builder okRequestBuilder = new Request.Builder(); boolean contentLengthSet = false; for (String name : request.headers.keySet()) { if (!contentLengthSet && "Content-Length".equals(name)) { contentLengthSet = true;/*from ww w . ja v a 2s . c o m*/ } okRequestBuilder.addHeader(name, request.headers.get(name)); } if (!contentLengthSet) { okRequestBuilder.addHeader("Content-Length", "0"); } RequestBody rb; switch (request.method) { case HttpRequest.GET: okRequestBuilder.get(); break; case HttpRequest.POST: rb = buildBody(contentType, request.body); //InputRequestBody rb = new InputRequestBody(contentType,request.body); okRequestBuilder.post(rb); break; case HttpRequest.PUT: rb = buildBody(contentType, request.body); okRequestBuilder.put(rb); break; case HttpRequest.DELETE: okRequestBuilder.delete(); break; case HttpRequest.PATCH: rb = buildBody(contentType, request.body); okRequestBuilder.patch(rb); break; } okRequestBuilder.url(request.url); Request okRequest = okRequestBuilder.build(); try { Response resp = mOkHttp.newCall(okRequest).execute(); Protocol protocol = resp.protocol(); ProtocolVersion pv; switch (protocol) { case HTTP_1_0: pv = new ProtocolVersion("HTTP", 1, 0); break; case HTTP_1_1: pv = new ProtocolVersion("HTTP", 1, 1); break; case HTTP_2: pv = new ProtocolVersion("HTTP", 2, 0); break; case SPDY_3: pv = new ProtocolVersion("spdy", 3, 1); break; default: throw new BaasIOException("Invalid protocol"); } StatusLine line = new BasicStatusLine(pv, resp.code(), resp.message()); BasicHttpResponse bresp = new BasicHttpResponse(line); bresp.setEntity(asEntity(resp)); for (String name : resp.headers().names()) { String val = resp.headers().get(name); bresp.addHeader(name, val); } return bresp; } catch (IOException e) { throw new BaasIOException(e); } }
From source file:com.baidu.oped.apm.plugin.okhttp.interceptor.HttpEngineReadResponseMethodInterceptor.java
License:Apache License
@Override public void after(Object target, Object[] args, Object result, Throwable throwable) { if (isDebug) { logger.afterInterceptor(target, args); }/*from w w w . j a v a 2 s . c o m*/ final Trace trace = traceContext.currentTraceObject(); if (trace == null) { return; } if (!validate(target)) { return; } try { SpanEventRecorder recorder = trace.currentSpanEventRecorder(); recorder.recordApi(methodDescriptor); recorder.recordException(throwable); if (statusCode) { Response response = ((UserResponseGetter) target)._$APM$_getUserResponse(); if (response != null) { recorder.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, response.code()); } } } finally { trace.traceBlockEnd(); } }