Search in sources :

Example 16 with RequestBody

use of com.squareup.okhttp.RequestBody in project QuickAndroid by ImKarl.

the class OkHttpCacheHelper method getResponse.

private static Response getResponse(OkHttpClient client, Request request) throws IOException {
    // Copy body metadata to the appropriate request headers.
    RequestBody body = request.body();
    if (body != null) {
        Request.Builder requestBuilder = request.newBuilder();
        MediaType contentType = body.contentType();
        if (contentType != null) {
            requestBuilder.header("Content-Type", contentType.toString());
        }
        long contentLength = body.contentLength();
        if (contentLength != -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
        } else {
            requestBuilder.header("Transfer-Encoding", "chunked");
            requestBuilder.removeHeader("Content-Length");
        }
        request = requestBuilder.build();
    }
    copyWithDefaults(client);
    // Create the initial HTTP engine. Retries and redirects need new engine
    // for each attempt.
    HttpEngine engine = new HttpEngine(client, request, false, false, false, null, null, null, null);
    int followUpCount = 0;
    while (true) {
        try {
            engine.sendRequest();
            engine.readResponse();
        } catch (RequestException e) {
            // The attempt to interpret the request failed. Give up.
            throw e.getCause();
        } catch (RouteException e) {
            // The attempt to connect via a route failed. The request will
            // not have been sent.
            HttpEngine retryEngine = engine.recover(e);
            if (retryEngine != null) {
                engine = retryEngine;
                continue;
            }
            // Give up; recovery is not possible.
            throw e.getLastConnectException();
        } catch (IOException e) {
            // An attempt to communicate with a server failed. The request
            // may have been sent.
            HttpEngine retryEngine = engine.recover(e, null);
            if (retryEngine != null) {
                engine = retryEngine;
                continue;
            }
            // Give up; recovery is not possible.
            throw e;
        }
        Response response = engine.getResponse();
        Request followUp = engine.followUpRequest();
        if (followUp == null) {
            return response;
        }
        if (++followUpCount > MAX_FOLLOW_UPS) {
            throw new ProtocolException("Too many follow-up requests: " + followUpCount);
        }
        if (!engine.sameConnection(followUp.httpUrl())) {
            engine.releaseConnection();
        }
        Connection connection = engine.close();
        request = followUp;
        engine = new HttpEngine(client, request, false, false, false, connection, null, null, response);
    }
}
Also used : RouteException(com.squareup.okhttp.internal.http.RouteException) ProtocolException(java.net.ProtocolException) HttpEngine(com.squareup.okhttp.internal.http.HttpEngine) Request(com.squareup.okhttp.Request) Connection(com.squareup.okhttp.Connection) IOException(java.io.IOException) RequestException(com.squareup.okhttp.internal.http.RequestException) Response(com.squareup.okhttp.Response) MediaType(com.squareup.okhttp.MediaType) RequestBody(com.squareup.okhttp.RequestBody)

Example 17 with RequestBody

use of com.squareup.okhttp.RequestBody in project LookLook by xinghongfei.

the class OkHttpUtils method buildPostRequest.

private Request buildPostRequest(String url, List<Param> params) {
    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (Param param : params) {
        builder.add(param.key, param.value);
    }
    RequestBody requestBody = builder.build();
    return new Request.Builder().url(url).post(requestBody).build();
}
Also used : Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) RequestBody(com.squareup.okhttp.RequestBody)

Example 18 with RequestBody

use of com.squareup.okhttp.RequestBody in project ETSMobile-Android2 by ApplETS.

the class ETSMobileAuthenticator method getAuthToken.

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
    // Extract the username and password from the Account Manager, and ask
    // the server for an appropriate AuthToken.
    final AccountManager am = AccountManager.get(mContext);
    String authToken = am.peekAuthToken(account, authTokenType);
    SecurePreferences securePreferences = new SecurePreferences(mContext);
    Date expirationDate = Utility.getDate(securePreferences, Constants.EXP_DATE_COOKIE, new Date());
    Date now = new Date();
    // Lets give another try to authenticate the user
    if (TextUtils.isEmpty(authToken) || expirationDate.before(now)) {
        final String password = am.getPassword(account);
        final String username = account.name;
        if (password != null) {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\n  \"Username\": \"" + username + "\",\n  \"Password\": \"" + password + "\"\n}");
            Request request = new Request.Builder().url(mContext.getString(R.string.portail_api_authentification_url)).post(body).addHeader("content-type", "application/json").addHeader("cache-control", "no-cache").build();
            Response httpResponse = null;
            try {
                httpResponse = client.newCall(request).execute();
                if (httpResponse.code() == 200) {
                    authToken = httpResponse.header("Set-Cookie");
                    Utility.saveCookieExpirationDate(authToken, securePreferences);
                    JSONObject jsonResponse = new JSONObject(httpResponse.body().string());
                    int typeUsagerId = jsonResponse.getInt("TypeUsagerId");
                    String domaine = jsonResponse.getString("Domaine");
                    securePreferences.edit().putInt(Constants.TYPE_USAGER_ID, typeUsagerId).commit();
                    securePreferences.edit().putString(Constants.DOMAINE, domaine).commit();
                    ApplicationManager.domaine = domaine;
                    ApplicationManager.typeUsagerId = typeUsagerId;
                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
                    boolean isTokenSent = sharedPreferences.getBoolean(Constants.IS_GCM_TOKEN_SENT_TO_SERVER, false);
                    if (!isTokenSent) {
                        Intent intent = new Intent(mContext, RegistrationIntentService.class);
                        mContext.startService(intent);
                    }
                } else {
                    Log.e("Erreur Portail", httpResponse.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    // If we get an authToken - we return it
    if (!TextUtils.isEmpty(authToken)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        return result;
    } else {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, null);
        return result;
    }
// If we get here, then we couldn't access the user's password - so we
// need to re-prompt them for their credentials. We do that by creating
// an intent to display our AuthenticatorActivity.
/*
        final Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        intent.putExtra(Constants.KEY_AUTH_TYPE, authTokenType);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
        return bundle;
        */
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) Request(com.squareup.okhttp.Request) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) Date(java.util.Date) AccountAuthenticatorResponse(android.accounts.AccountAuthenticatorResponse) Response(com.squareup.okhttp.Response) JSONObject(org.json.JSONObject) MediaType(com.squareup.okhttp.MediaType) AccountManager(android.accounts.AccountManager) RequestBody(com.squareup.okhttp.RequestBody)

Example 19 with RequestBody

use of com.squareup.okhttp.RequestBody in project pictureapp by EyeSeeTea.

the class PushClient method pushData.

/**
     * Pushes data to DHIS Server
     */
private JSONObject pushData(JSONObject data) throws Exception {
    Response response = null;
    final String DHIS_URL = getDhisURL();
    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);
    RequestBody body = RequestBody.create(JSON, data.toString());
    Request request = new Request.Builder().header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL).post(body).build();
    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Example 20 with RequestBody

use of com.squareup.okhttp.RequestBody in project pictureapp by EyeSeeTea.

the class BasicAuthenticator method executeCall.

/**
     * Call to DHIS Server
     */
static Response executeCall(JSONObject data, String url, String method) throws IOException {
    final String DHIS_URL = url;
    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);
    Request.Builder builder = new Request.Builder().header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL);
    switch(method) {
        case "POST":
            RequestBody postBody = RequestBody.create(JSON, data.toString());
            builder.post(postBody);
            break;
        case "PUT":
            RequestBody putBody = RequestBody.create(JSON, data.toString());
            builder.put(putBody);
            break;
        case "PATCH":
            RequestBody patchBody = RequestBody.create(JSON, data.toString());
            builder.patch(patchBody);
            break;
        case "GET":
            builder.get();
            break;
    }
    Request request = builder.build();
    return client.newCall(request).execute();
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

RequestBody (com.squareup.okhttp.RequestBody)20 Request (com.squareup.okhttp.Request)19 Response (com.squareup.okhttp.Response)13 IOException (java.io.IOException)13 OkHttpClient (com.squareup.okhttp.OkHttpClient)8 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 MediaType (com.squareup.okhttp.MediaType)3 MultipartBuilder (com.squareup.okhttp.MultipartBuilder)3 Intent (android.content.Intent)2 Call (com.squareup.okhttp.Call)2 CookieManager (java.net.CookieManager)2 BufferedSink (okio.BufferedSink)2 JSONException (org.json.JSONException)2 JSONObject (org.json.JSONObject)2 AccountAuthenticatorResponse (android.accounts.AccountAuthenticatorResponse)1 AccountManager (android.accounts.AccountManager)1 SharedPreferences (android.content.SharedPreferences)1 Bundle (android.os.Bundle)1 QAException (cn.jeesoft.qa.error.QAException)1