List of usage examples for com.squareup.okhttp Response isSuccessful
public boolean isSuccessful()
From source file:com.hkm.root.Tasks.upload_data.java
License:Open Source License
public void execute_upload(Request requestBuild) throws IOException, Exception { // executes generic request OkHttpClient use_client = client.clone(); use_client.setWriteTimeout(10, TimeUnit.SECONDS); Response response = use_client.newCall(requestBuild).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } else {//from www .ja v a 2s .c om if (!response.body().string().isEmpty()) { success_events_achieved++; // sb.append(response.body().string()); System.out.println(response.body().string()); // StandJsonResponse sp = new StandJsonResponse(); // sp.fromString(response.body().string()).setSingleSuccessAction(success_pass_event).run(); } else { throw new Exception("response body is empty"); } } }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request.java
License:Apache License
@Override protected Callback getCallback(final ResponseListener listener) { final RequestBody requestBody = savedRequestBody; final Request request = this; final Context ctx = this.context; return new Callback() { @Override// ww w . j a va 2 s. c o m public void onFailure(com.squareup.okhttp.Request request, IOException e) { if (listener != null) { listener.onFailure(null, e, null); } } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { if (listener == null) { return; } AuthorizationManager authorizationManager = BMSClient.getInstance().getAuthorizationManager(); int responseCode = response.code(); Map<String, List<String>> responseHeaders = response.headers().toMultimap(); boolean isAuthorizationRequired = authorizationManager.isAuthorizationRequired(responseCode, responseHeaders); if (isAuthorizationRequired) { if (oauthFailCounter++ < 2) { authorizationManager.obtainAuthorization(ctx, new ResponseListener() { @Override public void onSuccess(Response response) { // this will take the auth hader that has been cached by obtainAuthorizationHeader request.sendRequest(listener, requestBody); } @Override public void onFailure(Response response, Throwable t, JSONObject extendedInfo) { listener.onFailure(response, t, extendedInfo); } }); } else { listener.onFailure(new ResponseImpl(response), null, null); } } else { if (response.isSuccessful() || response.isRedirect()) { listener.onSuccess(new ResponseImpl(response)); } else { listener.onFailure(new ResponseImpl(response), null, null); } } } }; }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java
License:Apache License
protected Callback getCallback(final ResponseListener listener) { return new Callback() { @Override//from w ww. j av a 2 s.c o m public void onFailure(Request request, IOException e) { listener.onFailure(null, e, null); } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { if (response.isSuccessful() || response.isRedirect()) { listener.onSuccess(new ResponseImpl(response)); } else { listener.onFailure(new ResponseImpl(response), null, null); } } }; }
From source file:com.ibm.watson.developer_cloud.service.WatsonService.java
License:Open Source License
/** * Execute the HTTP request.//from w w w. j av a 2 s. co m * * @param request the HTTP request * * @return the HTTP response */ protected Response execute(Request request) { final Builder builder = request.newBuilder(); // Set service endpoint for relative paths if (RequestUtil.isRelative(request)) { builder.url(RequestUtil.replaceEndPoint(request.urlString(), getEndPoint())); } // Set default headers if (defaultHeaders != null) { for (String key : defaultHeaders.names()) builder.header(key, defaultHeaders.get(key)); } // Set User-Agent builder.header(HttpHeaders.USER_AGENT, getUserAgent()); // Set Authentication setAuthentication(builder); final Request newRequest = builder.build(); Response response; log.log(Level.FINEST, "Request to: " + newRequest.urlString()); try { response = client.newCall(newRequest).execute(); } catch (final IOException e) { log.log(Level.SEVERE, "IOException", e); throw new RuntimeException(e); } if (response.isSuccessful()) { return response; } final int status = response.code(); // There was a Client Error 4xx or a Server Error 5xx // Get the error message and create the exception final String error = getErrorMessage(response); log.log(Level.SEVERE, newRequest.urlString() + ", status: " + status + ", error: " + error); switch (status) { case HttpStatus.BAD_REQUEST: // HTTP 400 throw new BadRequestException(error != null ? error : "Bad Request", response); case HttpStatus.UNAUTHORIZED: // HTTP 401 throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials", response); case HttpStatus.FORBIDDEN: // HTTP 403 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response); case HttpStatus.NOT_FOUND: // HTTP 404 throw new NotFoundException(error != null ? error : "Not found", response); case HttpStatus.NOT_ACCEPTABLE: // HTTP 406 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response); case HttpStatus.CONFLICT: // HTTP 409 throw new ConflictException(error != null ? error : "", response); case HttpStatus.REQUEST_TOO_LONG: // HTTP 413 throw new RequestTooLargeException( error != null ? error : "Request too large: The request entity is larger than the server is able to process", response); case HttpStatus.UNSUPPORTED_MEDIA_TYPE: // HTTP 415 throw new UnsupportedException(error != null ? error : "Unsupported Media Type", response); case HttpStatus.TOO_MANY_REQUESTS: // HTTP 429 throw new TooManyRequestsException(error != null ? error : "Too many requests", response); case HttpStatus.INTERNAL_SERVER_ERROR: // HTTP 500 throw new InternalServerErrorException(error != null ? error : "Internal Server Error", response); case HttpStatus.SERVICE_UNAVAILABLE: // HTTP 503 throw new ServiceUnavailableException(error != null ? error : "Service Unavailable", response); default: // other errors throw new ServiceResponseException(status, error, response); } }
From source file:com.jkenneth.droidovpn.ui.activity.MainActivity.java
License:Open Source License
/** Displays the updated list of VPN servers */ private void getServerList() { mCall = mClient.newCall(mRequest);/*w ww . ja va2 s . co m*/ mCall.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { mHandler.post(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); } }); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { final List<Server> servers = CSVParser.parse(response); mHandler.post(new Runnable() { @Override public void run() { mServers.clear(); mServers.addAll(servers); mDatabase.save(servers); sort(mSortedBy); mSwipeRefreshLayout.setRefreshing(false); } }); } } }); }
From source file:com.liferay.mobile.sdk.SDKBuilder.java
License:Open Source License
public Discovery discover(String url, String context, int portalVersion) throws Exception { if ("portal".equals(context)) { context = ""; }/*from w w w .j av a 2 s . c o m*/ if (portalVersion == 62) { if (Validator.isNotNull(context)) { context = "/" + context; } url = String.format("%s%s/api/jsonws?discover", url, context); } else if (portalVersion == 7) { url = String.format("%s/api/jsonws?discover&contextName=%s", url, context); } OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected HTTP response: " + response); } if (portalVersion == 7) { JSONParser.registerTypeAdapter(Discovery.class, new DiscoveryDeserializer()); JSONParser.registerTypeAdapter(Action.class, new ActionDeserializer()); } return JSONParser.fromJSON(response.body().string(), Discovery.class); }
From source file:com.liuguangqiang.asyncokhttp.RequestTask.java
License:Apache License
public void execute() { try {/* w w w. ja v a 2 s . com*/ Response response = mClient.newCall(mRequest).execute(); mResponseHandler.sendStart(); int code = response.code(); String responseString = "without response body"; if (response.body() != null) responseString = response.body().string(); if (response.isSuccessful()) mResponseHandler.sendSuccess(code, responseString); else mResponseHandler.sendFailure(code, responseString); } catch (IOException e) { String error = "unknown"; if (e.getMessage() != null) error = e.getMessage(); if (error.equals("Canceled")) mResponseHandler.sendCancel(); else mResponseHandler.sendFailure(0, error); } }
From source file:com.magnet.max.android.rest.RequestInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Log.i(TAG, "---------Intercepting url : " + request.method() + " " + request.urlString()); CallOptions options = requestManager.popRequestOptions(request); boolean isCacheEnabled = null != options && null != options.getCacheOptions(); if (isCacheEnabled) { if (options.getCacheOptions().isAlwaysUseCacheIfOffline() && ConnectivityManager.getInstance() .getConnectivityStatus() == ConnectivityManager.TYPE_NOT_CONNECTED) { Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions()); if (null != cachedResponse) { Log.d(TAG, "-------return from cache when isAlwaysUseCacheIfOffline==true and offline"); return cachedResponse; } else { throw new IOException("It's offline and no cached response found"); }// ww w . j a v a2 s . c om } else if (options.getCacheOptions().getMaxCacheAge() > 0) { // Return from cache if it's not expired Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions()); if (null != cachedResponse) { Log.d(TAG, "-------return from cache when maxCacheAge = " + options.getCacheOptions().getMaxCacheAge()); return cachedResponse; } } } //Add auth token for network call String token = null; if ((authTokenProvider.isAuthEnabled() && authTokenProvider.isAuthRequired(request)) && (null != authTokenProvider.getAppToken() || null != authTokenProvider.getUserToken())) { String existingToken = request.header(AuthUtil.AUTHORIZATION_HEADER); if (null != existingToken && existingToken.startsWith("Basic")) { // Already has Basic Auth header, don't overwrite } else { token = getToken(); } } boolean useMock = false; if (null != options) { if (isCacheEnabled) { useMock = options.getCacheOptions().useMock(); } else if (null != options.getReliableCallOptions()) { useMock = options.getReliableCallOptions().useMock(); } } Response response = null; long startTime = System.currentTimeMillis(); try { // Modify request if (null != token || useMock) { Request.Builder newRequestBuilder = chain.request().newBuilder(); if (null != token) { newRequestBuilder.header(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(token)); } if (useMock) { newRequestBuilder.url(request.urlString().replace(RestConstants.REST_BASE_PATH, RestConstants.REST_MOCK_BASE_PATH)); } response = chain.proceed(newRequestBuilder.build()); } else { response = chain.proceed(request); } if (null != options && options.isReliable()) { // Reliable call requestManager.removeReliableRequest(request); } } catch (IOException e) { //if(null != options && options.isReliable()) { // Reliable call // requestManager.saveReliableRequest(request, null, null, options.getReliableCallOptions(), e.getMessage()); // //TODO : // return null; // Swallow exception //} else { // throw e; //} Log.e(TAG, "error when getting response", e); throw e; } Log.d(TAG, "---------Response for url : " + request.method() + " " + request.urlString() + " : code = " + response.code() + ", message = " + response.message() + " in " + (System.currentTimeMillis() - startTime) + " ms"); //Save/Update response in cache if (response.isSuccessful() && isCacheEnabled && (options.getCacheOptions().getMaxCacheAge() > 0 || options.getCacheOptions().isAlwaysUseCacheIfOffline())) { return cacheManager.cacheResponse(request, response, options.getCacheOptions()); } return response; }
From source file:com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.java
License:Apache License
public Departures find(Context context, Site site) throws IllegalArgumentException, IOException { if (site == null) { Log.w(TAG, "Site is null"); throw new IllegalArgumentException(TAG + ", Site is null"); }//ww w .j av a 2 s . c om Log.d(TAG, "About to get departures for " + site.getName()); String endpoint = apiEndpoint2() + "v1/departures/" + site.getId() + "?key=" + get(KEY) + "&timewindow=30"; HttpHelper httpHelper = HttpHelper.getInstance(context); Request request = httpHelper.createRequest(endpoint); OkHttpClient client = httpHelper.getClient(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { Log.w(TAG, "A remote server error occurred when getting departures, status code: " + response.code()); throw new IOException("A remote server error occurred when getting departures."); } Departures departures; String rawContent = response.body().string(); try { departures = Departures.fromJson(new JSONObject(rawContent)); } catch (JSONException e) { Crashlytics.logException(e); Log.d(TAG, "Could not parse the departure reponse."); throw new IOException("Could not parse the response."); } return departures; }
From source file:com.meyersj.tamalenow.location.UpdateLocationService.java
License:Open Source License
public void postLocation(Location location) { String date = Utils.dateFormat.format(new Date()); Log.d(TAG, date);//from w w w .ja v a 2 s . com RequestBody formBody = new FormEncodingBuilder().add("vendor_id", "test_vendor") .add("tstamp", Utils.dateFormat.format(new Date())) .add("lat", String.valueOf(location.getLatitude())) .add("lon", String.valueOf(location.getLongitude())).build(); Request request = new Request.Builder().url(app.getAPIBase() + "/" + Endpoints.LOCATION).post(formBody) .build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.d(TAG, "failure"); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Log.d(TAG, response.body().string()); } }); }