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:net.yatomiya.nicherry.services.bbs.ModelUpdateHandler.java

License:Open Source License

protected boolean handleValidateResponse(Response response) {
    switch (response.code()) {
    case 200: // OK
        return true;
    case 304: // Not_Modified
        updateEvent.setType(UpdateEvent.Type.NOT_MODIFIED);
        return false;
    default:/*  ww w  .j  a  va2  s .c  om*/
        updateEvent.setType(UpdateEvent.Type.STATUS_ERROR);
        return false;
    }
}

From source file:net.yatomiya.nicherry.services.bbs.PostEvent.java

License:Open Source License

void setupWithResponse(MODEL model, Request request, Response response, String responseHtml) {
    this.model = model;
    this.request = request;
    this.response = response;
    this.responseHtml = responseHtml;

    if (response.code() == 200) {
        responseDocument = Jsoup.parse(responseHtml);

        title = JUtils.nonNull(findTitle(responseHtml));
        xTag = JUtils.nonNull(findXTag(responseHtml));

        if (title.contains("???????") || xTag.equals("true")) {
            type = Type.SUCCESS;//from  w  w w.j a v  a  2s  . co m
        } else if (title.contains("????") || xTag.equals("cookie")) {
            type = Type.CONFIRM;
        } else {
            type = Type.SCRIPT_ERROR;
        }
    } else {
        type = Type.STATUS_ERROR;
    }

    postTime = JUtils.getCurrentTime();
}

From source file:net.yatomiya.nicherry.services.bbs.PostMessageHandler.java

License:Open Source License

void doOnResponse(Response response) {
    int statusCode = response.code();

    try {//from   w w  w. j av a 2 s.c o  m
        String responseBody = StringUtils.getString(response.body().bytes(), NConstants.CHARSET_SHIFT_JIS);
        postEvent.setupWithResponse(getModel(), response.request(), response, responseBody);
    } catch (Exception e) {
        postEvent.setupConnectionError(getModel(), response.request(), e);
    }

    doFinish();
}

From source file:net.yatomiya.nicherry.services.bbs.ThreadUpdateHandler.java

License:Open Source License

Response processIntercept(Interceptor.Chain chain) throws IOException {
    Response response = null;
    Request.Builder builder = chain.request().newBuilder();

    if (!isForceUpdate()) {
        // try delta get.
        byte[] tail = getProcessor().getDatTail().getTail();
        if (tail.length > 0) {
            File datFile = getProcessor().getDatFile();
            if (IOUtils.isFileExists(datFile)) {
                long datLen = datFile.length();
                if (datLen > 0) {
                    long getStartOffset = datLen - tail.length;
                    if (getStartOffset > 0) {
                        builder.header("Range", "bytes=" + getStartOffset + "-");

                        // Disable gzip compression. Gzip compression and partial get can't co-exist.
                        // Header with empty value must be set. If header is not set, HttpClient default implementation
                        // adds header with value accepting gzip format automatically.
                        builder.header("Accept-Encoding", "");

                        response = chain.proceed(builder.build());

                        switch (response.code()) {
                        case 200: // OK
                        case 206: // Partial Content
                            // check contents.
                            contents = response.body().bytes();

                            if (contents.length < tail.length
                                    || !Arrays.equals(tail, Arrays.copyOfRange(contents, 0, tail.length))) {
                                // Tail data of local dat is different from server, we must get whole dat.
                                // That means local dat is NOT identical to dat in server, something is modified in server.
                                // So we must get whole dat from server again.
                                // If region except stored in tail is modified in server, and length of dat in server equals to dat in local,
                                // we can't find out those differences.

                                contents = null;
                            } else {
                                // delta contents is valid.
                                isDeltaGetSuccess = true;
                                return response;
                            }//from   w w  w  .j av a 2s  . c om
                            break;
                        case 304: // Not Modified
                            // Not modified, so no need to update.
                            return response;
                        case 416: // Range Not Satisfied
                        default:
                            // Failed.
                            break;
                        }
                    }
                }
            }
        }
    }

    // do get all
    return chain.proceed(chain.request());
}

From source file:net.yatomiya.nicherry.services.bbs.ThreadUpdateHandler.java

License:Open Source License

@Override
protected boolean handleValidateResponse(Response response) {
    if (isDeltaGetSuccess && response.code() == 206) {
        return true;
    }//from   w w w . j a va 2 s  .  c  o m
    return super.handleValidateResponse(response);
}

From source file:objective.taskboard.jira.endpoint.JiraEndpoint.java

License:Open Source License

public <S> S request(Class<S> service, String username, String password) {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(60, TimeUnit.SECONDS);
    client.setConnectTimeout(60, TimeUnit.SECONDS);
    client.interceptors().add(new AuthenticationInterceptor(username, password));
    client.interceptors().add(new Interceptor() {
        @Override/*  www  .  j  a v  a2  s  .  c o  m*/
        public Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Request request = chain.request();
            Response response = chain.proceed(request);

            int retryCount = 0;
            while (response.code() == HttpStatus.GATEWAY_TIMEOUT.value() && retryCount < 3) {
                Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
                response = chain.proceed(request);
                retryCount++;
            }
            if (!response.isSuccessful())
                log.error(request.urlString() + " request failed.");

            return response;
        }
    });

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new TaskboardJacksonModule());
    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(jiraProperties.getUrl())
            .setConverter(new JacksonConverter(objectMapper)).setClient(new OkClient(client)).build();

    return retrofit.create(service);
}

From source file:org.addhen.smssync.data.net.AppHttpClient.java

License:Open Source License

private Boolean request(SyncUrl syncUrl) {
    initTestRequest(syncUrl);/*from   ww  w.ja  v a 2s. c o  m*/
    Boolean status = false;
    try {
        execute();
    } catch (Exception e) {
        log("Request failed", e);
    }
    Response response = getResponse();
    if (response != null) {
        int statusCode = response.code();
        if (statusCode == 200) {
            final Gson gson = new Gson();
            SmssyncResponse smssyncResponses = null;
            try {
                smssyncResponses = gson.fromJson(response.body().charStream(), SmssyncResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
            if (smssyncResponses != null && smssyncResponses.getPayload() != null) {
                if (smssyncResponses.getPayload().isSuccess() || !smssyncResponses.getPayload().isSuccess()) {
                    status = true;
                }
            }
        }
    }
    return status;
}

From source file:org.addhen.smssync.data.net.MessageHttpClient.java

License:Open Source License

/**
 * Post sms to the configured sync URL/*from   w  w  w  . jav a 2 s  .co  m*/
 *
 * @return boolean
 */
public boolean postSmsToWebService(SyncUrl syncUrl, Message message, String toNumber, String deviceId) {
    Logger.log(MessageHttpClient.class.getSimpleName(), "posting messages");
    initRequest(syncUrl, message, toNumber, deviceId);
    final Gson gson = new Gson();
    try {
        execute();
        Response response = getResponse();
        int statusCode = response.code();
        if (statusCode != 200 && statusCode != 201) {
            setServerError("bad http return code", statusCode);
            return false;
        }

        SmssyncResponse smssyncResponses = gson.fromJson(response.body().string(), SmssyncResponse.class);
        if (smssyncResponses.getPayload().isSuccess()) {
            // auto response message is enabled to be received from the
            // server.
            setServerSuccessResp(smssyncResponses);
            return true;
        }

        String payloadError = smssyncResponses.getPayload().getError();
        if (!TextUtils.isEmpty(payloadError)) {
            setServerError(payloadError, statusCode);
        } else {
            setServerError(response.body().string(), statusCode);
        }
    } catch (Exception e) {
        Observable.error(e);
        log("Request failed", e);
        setClientError("Request failed. " + e.getMessage());
    }
    return false;

}

From source file:org.addhen.smssync.net.MessageSyncHttpClient.java

License:Open Source License

/**
 * Post sms to the configured sync URL/*from   ww w  . j  a v  a  2s  .  c om*/
 *
 * @return boolean
 */
public boolean postSmsToWebService() {

    try {
        execute();
        Response response = getResponse();
        int statusCode = response.code();

        if (statusCode != 200 && statusCode != 201) {
            setServerError("bad http return code", statusCode);
            return false;
        }
        final Gson gson = new Gson();
        SmssyncResponse smssyncResponses = gson.fromJson(response.body().charStream(), SmssyncResponse.class);
        if (smssyncResponses.getPayload().isSuccess()) {
            // auto response message is enabled to be received from the
            // server.
            setServerSuccessResp(smssyncResponses);
            return true;
        }

        String payloadError = smssyncResponses.getPayload().getError();
        if (!TextUtils.isEmpty(payloadError)) {
            setServerError(payloadError, statusCode);
        } else {
            setServerError(response.body().string(), statusCode);
        }
    } catch (Exception e) {
        log("Request failed", e);
        setClientError("Request failed. " + e.getMessage());
    }

    return false;

}

From source file:org.apache.hadoop.hdfs.web.oauth2.ConfRefreshTokenBasedAccessTokenProvider.java

License:Apache License

void refresh() throws IOException {
    try {/*from   w  ww .  j  a  v a2  s .  co m*/
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);

        String bodyString = Utils.postBody(GRANT_TYPE, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken, CLIENT_ID,
                clientId);

        RequestBody body = RequestBody.create(URLENCODED, bodyString);

        Request request = new Request.Builder().url(refreshURL).post(body).build();
        Response responseBody = client.newCall(request).execute();

        if (responseBody.code() != HttpStatus.SC_OK) {
            throw new IllegalArgumentException("Received invalid http response: " + responseBody.code()
                    + ", text = " + responseBody.toString());
        }

        Map<?, ?> response = READER.readValue(responseBody.body().string());

        String newExpiresIn = response.get(EXPIRES_IN).toString();
        accessTokenTimer.setExpiresIn(newExpiresIn);

        accessToken = response.get(ACCESS_TOKEN).toString();
    } catch (Exception e) {
        throw new IOException("Exception while refreshing access token", e);
    }
}