Search in sources :

Example 66 with MediaType

use of okhttp3.MediaType in project ETSMobile-Android2 by ApplETS.

the class AuthentificationPortailTask method doInBackground.

protected Intent doInBackground(String... params) {
    OkHttpClient client = TLSUtilities.createETSOkHttpClient(launchingActivity);
    String url = params[0], username = params[1], password = params[2];
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, "{\n  \"Username\": \"" + username + "\",\n  \"Password\": \"" + password + "\"\n}");
    Request request = new Request.Builder().url(url).post(body).addHeader("content-type", "application/json").addHeader("cache-control", "no-cache").build();
    Response response = null;
    String authCookie = "", domaine = "";
    int typeUsagerId = 0;
    final Intent res = new Intent();
    try {
        response = client.newCall(request).execute();
        if (response.code() == 200) {
            List<String> cookies = response.headers().values("Set-Cookie");
            for (String cookie : cookies) {
                if (cookie.contains(Constants.MONETS_COOKIE_NAME)) {
                    authCookie = cookie;
                    break;
                }
            }
            JSONObject jsonResponse = new JSONObject(response.body().string());
            typeUsagerId = jsonResponse.getInt("TypeUsagerId");
            domaine = jsonResponse.getString("Domaine");
            res.putExtra(AccountManager.KEY_AUTHTOKEN, authCookie);
            res.putExtra(Constants.TYPE_USAGER_ID, typeUsagerId);
            res.putExtra(Constants.DOMAINE, domaine);
        } else {
            Log.e("Erreur Portail", response.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    res.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
    res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    res.putExtra(Constants.PARAM_USER_PASS, password);
    return res;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 67 with MediaType

use of okhttp3.MediaType in project Douya by DreaminginCodeZH.

the class ImageTypeUriRequestBody method contentType.

@Nullable
@Override
public MediaType contentType() {
    MediaType superType = super.contentType();
    if (superType != null) {
        return superType;
    }
    String mimeType = UriUtils.getType(mUri, mContentResolver);
    if (TextUtils.isEmpty(mimeType)) {
        try (InputStream inputStream = mContentResolver.openInputStream(mUri)) {
            mimeType = FileTypeUtils.getImageMimeType(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (!TextUtils.isEmpty(mimeType)) {
        return MediaType.parse(mimeType);
    }
    return null;
}
Also used : InputStream(java.io.InputStream) MediaType(okhttp3.MediaType) Nullable(androidx.annotation.Nullable)

Example 68 with MediaType

use of okhttp3.MediaType in project yyl_example by Relucent.

the class TraceInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    System.out.println("/==========TraceInterceptor==========");
    System.out.println("\nRequest:");
    System.out.println(request.method());
    System.out.println(request.url());
    System.out.println(request.headers());
    RequestBody requestBody = request.body();
    if (requestBody != null) {
        try (Buffer buffer = new Buffer()) {
            requestBody.writeTo(buffer);
            String content = buffer.readUtf8();
            System.out.println(content);
            requestBody = RequestBody.create(content, requestBody.contentType());
        }
    }
    request = request.newBuilder().method(request.method(), requestBody).build();
    Response response = chain.proceed(request);
    MediaType mediaType = response.body().contentType();
    String content = response.body().string();
    System.out.println("\nResponse:");
    System.out.println(response.headers());
    System.out.println(content);
    System.out.println("==========TraceInterceptor==========/\n\n\n\n\n");
    return response.newBuilder().body(ResponseBody.create(content, mediaType)).build();
}
Also used : Buffer(okio.Buffer) Response(okhttp3.Response) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 69 with MediaType

use of okhttp3.MediaType in project Conversations by siacs.

the class AbstractConnectionManager method requestBody.

// For progress tracking see:
// https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
public static RequestBody requestBody(final DownloadableFile file, final ProgressListener progressListener) {
    return new RequestBody() {

        @Override
        public long contentLength() {
            return file.getSize() + (file.getKey() != null ? 16 : 0);
        }

        @Nullable
        @Override
        public MediaType contentType() {
            return MediaType.parse(file.getMimeType());
        }

        @Override
        public void writeTo(final BufferedSink sink) throws IOException {
            long transmitted = 0;
            try (final Source source = Okio.source(upgrade(file, new FileInputStream(file)))) {
                long read;
                while ((read = source.read(sink.buffer(), 8196)) != -1) {
                    transmitted += read;
                    sink.flush();
                    progressListener.onProgress(transmitted);
                }
            }
        }
    };
}
Also used : BufferedSink(okio.BufferedSink) Source(okio.Source) FileInputStream(java.io.FileInputStream) RequestBody(okhttp3.RequestBody)

Example 70 with MediaType

use of okhttp3.MediaType in project picasso by square.

the class NetworkRequestHandlerTest method unknownContentLengthFromDiskThrows.

@Test
public void unknownContentLengthFromDiskThrows() throws Exception {
    final AtomicBoolean closed = new AtomicBoolean();
    ResponseBody body = new ResponseBody() {

        @Override
        public MediaType contentType() {
            return null;
        }

        @Override
        public long contentLength() {
            return 0;
        }

        @Override
        public BufferedSource source() {
            return new Buffer();
        }

        @Override
        public void close() {
            closed.set(true);
            super.close();
        }
    };
    responses.add(responseOf(body).newBuilder().cacheResponse(responseOf(null)).build());
    Action action = TestUtils.mockAction(URI_KEY_1, URI_1);
    final CountDownLatch latch = new CountDownLatch(1);
    networkHandler.load(picasso, action.request, new RequestHandler.Callback() {

        @Override
        public void onSuccess(Result result) {
            throw new AssertionError();
        }

        @Override
        public void onError(@NonNull Throwable t) {
            verify(picasso, never()).downloadFinished(anyInt());
            assertTrue(closed.get());
            latch.countDown();
        }
    });
    assertThat(latch.await(10, SECONDS)).isTrue();
}
Also used : Buffer(okio.Buffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CountDownLatch(java.util.concurrent.CountDownLatch) ResponseBody(okhttp3.ResponseBody) Result(com.squareup.picasso3.RequestHandler.Result) Test(org.junit.Test)

Aggregations

MediaType (okhttp3.MediaType)103 RequestBody (okhttp3.RequestBody)95 Request (okhttp3.Request)86 Response (okhttp3.Response)78 IOException (java.io.IOException)73 ResponseBody (okhttp3.ResponseBody)36 BufferedSink (okio.BufferedSink)34 Buffer (okio.Buffer)30 Charset (java.nio.charset.Charset)26 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)17 OkHttpClient (okhttp3.OkHttpClient)17 InputStream (java.io.InputStream)12 HashMap (java.util.HashMap)12 MultipartBody (okhttp3.MultipartBody)12 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 GzipSink (okio.GzipSink)10 JSONObject (org.json.JSONObject)10