Example usage for com.squareup.okhttp Response code

List of usage examples for com.squareup.okhttp Response code

Introduction

In this page you can find the example usage for com.squareup.okhttp Response code.

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:com.magnet.max.android.rest.qos.internal.CachedResponse.java

License:Apache License

public CachedResponse(Response response) {
    this.code = response.code();
    this.protocol = response.protocol().toString();
    this.message = response.message();

    parseHeaders(response.headers());/*from w  w  w .  j  a  v  a  2  s  .com*/

    if (null != response.body()) {
        try {
            Buffer buffer = new Buffer();
            response.body().source().readAll(buffer);
            body = CacheUtils.copyBody(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.magnet.max.android.rest.qos.internal.CacheManager.java

License:Apache License

public Response cacheResponse(Request request, Response response, CacheOptions options) {
    String requestHash = CacheUtils.getRequestHash(request);
    ResponseCacheEntity operation = findLatestCache(requestHash, request, options);
    long currentTimestamp = System.currentTimeMillis();
    if (null == operation) {
        operation = new ResponseCacheEntity();
        operation.createdAt = currentTimestamp;
        operation.url = request.urlString();
        operation.httpMethod = request.method();
        operation.requestHash = requestHash;
        operation.response = new CachedResponse(response);
        operation.responseCode = response.code();
        operation.isOfflineCache = options.isAlwaysUseCacheIfOffline();

        Log.d(TAG, "Adding cache for request " + request);
    } else {/*from  ww  w  . j ava  2 s.  c o m*/
        //Update body
        operation.response = new CachedResponse(response);
        Log.d(TAG, "Updating cache for request " + request);
    }
    operation.updatedAt = currentTimestamp;
    long newExpiredTime = 0;
    if (options.getMaxCacheAge() > 0) {
        newExpiredTime = currentTimestamp + options.getMaxCacheAge() * 1000;
    }
    if (null == operation.getExpiredAt() || newExpiredTime > operation.getExpiredAt()) {
        operation.expiredAt = newExpiredTime;
    }
    operation.save();

    if (null != response.body()) {
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), operation.response.body)).build();
    } else {
        return response;
    }
}

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");
            }/* w  w  w  .  j  ava2  s  .c o m*/
        } 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.mamashai.pingxx.PingxxAndroidModule.java

License:Open Source License

@Kroll.method
public void pay(Object arg) {
    HashMap<String, String> kd = (HashMap<String, String>) arg;

    OkHttpClient client = new OkHttpClient();

    /*//from  w  w  w .  jav  a2  s .  co m
    RequestBody formBody = new FormEncodingBuilder()
      .add("order_no", kd.get("order_no"))
      .add("amount", kd.get("amount"))
      .add("channel", kd.get("channel"))
      .build();
            
    Request request = new Request.Builder().url(url).build();
      Response response = client.newCall(request).execute();
    */

    String url = kd.get("url") + "?order_no=" + kd.get("order_no") + "&amount=" + kd.get("amount") + "&channel="
            + kd.get("channel");
    Log.d(LCAT, "url :" + url);
    Request request = new Request.Builder().url(url).build();

    try {
        Response response = client.newCall(request).execute();
        if (response.code() >= 200 && response.code() <= 300) {
            String data = response.body().string();
            Log.d(LCAT, "data:" + data);

            Intent intent = new Intent();
            String packageName = _app.getAppCurrentActivity().getPackageName();
            ComponentName componentName = new ComponentName(packageName,
                    packageName + ".wxapi.WXPayEntryActivity");
            intent.setComponent(componentName);
            intent.putExtra(PaymentActivity.EXTRA_CHARGE, data);

            TiActivitySupport support = (TiActivitySupport) TiApplication.getAppCurrentActivity();
            support.launchActivityForResult(intent, REQUEST_CODE_PAYMENT, this);
            Log.d(LCAT, "after launch Activity");
        } else {
            HashMap<String, Object> event = new HashMap<String, Object>();
            event.put("code", "error");
            event.put("text", "charge" + response);
            fireEvent("ping_paid", event);
            Log.d(LCAT, "request error");
        }
    } catch (Exception e) {
    }
}

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  .ja  va2  s . c  o m*/

    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.markupartist.sthlmtraveling.provider.planner.Planner.java

License:Apache License

public Trip2 addIntermediateStops(final Context context, Trip2 trip, JourneyQuery query) throws IOException {
    Uri u = Uri.parse(apiEndpoint2());//from w  w  w . j ava  2  s.c  o m
    Uri.Builder b = u.buildUpon();
    b.appendEncodedPath("journey/v1/intermediate/");
    b.appendQueryParameter("ident", query.ident);
    b.appendQueryParameter("seqnr", query.seqnr);
    int references = 0;
    String reference = null;
    for (SubTrip st : trip.subTrips) {
        if ((!TextUtils.isEmpty(st.reference)) && st.intermediateStop.isEmpty()) {
            b.appendQueryParameter("reference", st.reference);
            references++;
            reference = st.reference;
        }
    }
    u = b.build();

    if (references == 0) {
        return trip;
    }

    HttpHelper httpHelper = HttpHelper.getInstance(context);
    com.squareup.okhttp.Response response = httpHelper.getClient()
            .newCall(httpHelper.createRequest(u.toString())).execute();

    String rawContent;
    int statusCode = response.code();
    switch (statusCode) {
    case 200:
        rawContent = response.body().string();
        try {
            JSONObject baseResponse = new JSONObject(rawContent);
            if (baseResponse.has("stops")) {
                if (baseResponse.isNull("stops")) {
                    Log.d(TAG, "stops was null, ignoring.");
                } else if (references == 1) {
                    JSONArray intermediateStopsJson = baseResponse.getJSONArray("stops");
                    for (SubTrip st : trip.subTrips) {
                        if (reference.equals(st.reference)) {
                            for (int i = 0; i < intermediateStopsJson.length(); i++) {
                                st.intermediateStop
                                        .add(IntermediateStop.fromJson(intermediateStopsJson.getJSONObject(i)));
                            }
                        }
                    }
                } else {
                    JSONObject intermediateStopsJson = baseResponse.getJSONObject("stops");
                    for (SubTrip st : trip.subTrips) {
                        if (intermediateStopsJson.has(st.reference)) {
                            JSONArray jsonArray = intermediateStopsJson.getJSONArray(st.reference);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                st.intermediateStop.add(IntermediateStop.fromJson(jsonArray.getJSONObject(i)));
                            }
                        }
                    }
                }

            } else {
                Log.w(TAG, "Invalid response when fetching intermediate stops.");
            }
        } catch (JSONException e) {
            Log.w(TAG, "Could not parse the response for intermediate stops.");
        }
        break;
    case 400: // Bad request
        rawContent = response.body().string();
        try {
            BadResponse br = BadResponse.fromJson(new JSONObject(rawContent));
            Log.e(TAG, "Invalid error response for intermediate stops: " + br.toString());
        } catch (JSONException e) {
            Log.e(TAG, "Could not parse the error response for intermediate stops.");
        }
    default:
        Log.e(TAG, "Status code not OK from intermediate stops API, was " + statusCode);
    }

    return trip;
}

From source file:com.markupartist.sthlmtraveling.provider.planner.Planner.java

License:Apache License

public SubTrip addIntermediateStops(Context context, SubTrip subTrip, JourneyQuery query) throws IOException {
    Uri u = Uri.parse(apiEndpoint2());//w w  w .j  a  v a2  s.c  om
    Uri.Builder b = u.buildUpon();
    b.appendEncodedPath("journey/v1/intermediate/");
    b.appendQueryParameter("ident", query.ident);
    b.appendQueryParameter("seqnr", query.seqnr);
    b.appendQueryParameter("reference", subTrip.reference);

    u = b.build();

    HttpHelper httpHelper = HttpHelper.getInstance(context);
    com.squareup.okhttp.Response response = httpHelper.getClient()
            .newCall(httpHelper.createRequest(u.toString())).execute();

    String rawContent;
    int statusCode = response.code();
    switch (statusCode) {
    case 200:
        rawContent = response.body().string();
        try {
            JSONObject baseResponse = new JSONObject(rawContent);
            if (baseResponse.has("stops")) {
                JSONArray intermediateStopJsonArray = baseResponse.getJSONArray("stops");
                for (int i = 0; i < intermediateStopJsonArray.length(); i++) {
                    subTrip.intermediateStop
                            .add(IntermediateStop.fromJson(intermediateStopJsonArray.getJSONObject(i)));
                }
            } else {
                Log.w(TAG, "Invalid response when fetching intermediate stops.");
            }
        } catch (JSONException e) {
            Log.w(TAG, "Could not parse the reponse for intermediate stops.");
        }
        break;
    case 400:
        rawContent = response.body().string();
        try {
            BadResponse br = BadResponse.fromJson(new JSONObject(rawContent));
            Log.e(TAG, "Invalid response for intermediate stops: " + br.toString());
        } catch (JSONException e) {
            Log.e(TAG, "Could not parse the reponse for intermediate stops.");
        }
    default:
        Log.e(TAG, "Status code not OK from intermediate stops API, was " + statusCode);
    }

    return subTrip;
}

From source file:com.markupartist.sthlmtraveling.provider.planner.Planner.java

License:Apache License

private Response doJourneyQuery(final Context context, JourneyQuery query, int scrollDirection)
        throws IOException, BadResponse {

    Uri u = Uri.parse(apiEndpoint2());/*w  w w  . j a v  a2  s  .  c  om*/
    Uri.Builder b = u.buildUpon();
    b.appendEncodedPath("v1/journey/");
    if (scrollDirection > -1) {
        b.appendQueryParameter("dir", String.valueOf(scrollDirection));
        b.appendQueryParameter("ident", query.ident);
        b.appendQueryParameter("seq", query.seqnr);
    } else {
        if (shouldUseIdInQuery(query.origin)) {
            b.appendQueryParameter("origin", query.origin.getId());
        } else if (query.origin.hasLocation()) {
            b.appendQueryParameter("origin", query.origin.getName());
            b.appendQueryParameter("origin_latitude", String.valueOf(query.origin.getLocation().getLatitude()));
            b.appendQueryParameter("origin_longitude",
                    String.valueOf(query.origin.getLocation().getLongitude()));
        } else {
            b.appendQueryParameter("origin", query.origin.getNameOrId());
        }
        if (shouldUseIdInQuery(query.destination)) {
            b.appendQueryParameter("destination", query.destination.getId());
        } else if (query.destination.hasLocation()) {
            b.appendQueryParameter("destination", query.destination.getName());
            b.appendQueryParameter("destination_latitude",
                    String.valueOf(query.destination.getLocation().getLatitude()));
            b.appendQueryParameter("destination_longitude",
                    String.valueOf(query.destination.getLocation().getLongitude()));
        } else {
            b.appendQueryParameter("destination", query.destination.getNameOrId());
        }
        for (String transportMode : query.transportModes) {
            b.appendQueryParameter("transport", transportMode);
        }
        if (query.time != null) {
            b.appendQueryParameter("date", DATE_FORMAT.format(query.time));
            b.appendQueryParameter("time", TIME_FORMAT.format(query.time));
        }
        if (!query.isTimeDeparture) {
            b.appendQueryParameter("arrival", "1");
        }
        if (query.hasVia()) {
            if (query.via.getId() == null) {
                b.appendQueryParameter("via", query.via.getName());
            } else {
                b.appendQueryParameter("via", String.valueOf(query.via.getId()));
            }
        }
        if (query.alternativeStops) {
            b.appendQueryParameter("alternative", "1");
        }
    }

    b.appendQueryParameter("with_site_id", "1");

    // Include intermediate stops.
    //b.appendQueryParameter("intermediate_stops", "1");

    u = b.build();

    //Log.e(TAG, "Query: " + query.toString());
    //Log.e(TAG, "Query: " + u.toString());

    HttpHelper httpHelper = HttpHelper.getInstance(context);
    com.squareup.okhttp.Response response = httpHelper.getClient()
            .newCall(httpHelper.createRequest(u.toString())).execute();

    Response r = null;
    String rawContent;
    int statusCode = response.code();
    switch (statusCode) {
    case 200:
        rawContent = response.body().string();
        try {
            JSONObject baseResponse = new JSONObject(rawContent);
            if (baseResponse.has("journey")) {
                r = Response.fromJson(baseResponse.getJSONObject("journey"));
            } else {
                Log.w(TAG, "Invalid response");
            }
        } catch (JSONException e) {
            Log.d(TAG, "Could not parse the reponse...");
            throw new IOException("Could not parse the response.");
        }
        break;
    case 400:
        rawContent = response.body().string();
        BadResponse br;
        try {
            br = BadResponse.fromJson(new JSONObject(rawContent));
        } catch (JSONException e) {
            Log.d(TAG, "Could not parse the reponse...");
            throw new IOException("Could not parse the response.");
        }
        throw br;
    default:
        Log.d(TAG, "Status code not OK from API, was " + statusCode);
        throw new IOException("A remote server error occurred when getting deviations.");
    }

    return r;
}

From source file:com.microsoft.rest.credentials.ApplicationTokenCredentialsInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    if (credentials.getToken() == null) {
        credentials.setToken(acquireAccessToken(chain.request()));
    }/* w  ww  . java  2 s  . co  m*/
    Response response = sendRequestWithAuthorization(chain);
    if (response == null || response.code() == 401) {
        credentials.setToken(acquireAccessToken(chain.request()));
        response = sendRequestWithAuthorization(chain);
    }
    return response;
}

From source file:com.microsoft.rest.credentials.TokenCredentialsInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    Response response = sendRequestWithAuthorization(chain);
    if (response == null || response.code() == 401) {
        credentials.refreshToken();//from  w w w  .  j a  va2s.co m
        response = sendRequestWithAuthorization(chain);
    }
    return response;
}