Search in sources :

Example 1 with MediaType

use of okhttp3.MediaType in project buck by facebook.

the class HttpArtifactCache method storeImpl.

@Override
protected void storeImpl(ArtifactInfo info, final Path file, final Finished.Builder eventBuilder) throws IOException {
    // Build the request, hitting the multi-key endpoint.
    Request.Builder builder = new Request.Builder();
    final HttpArtifactCacheBinaryProtocol.StoreRequest storeRequest = new HttpArtifactCacheBinaryProtocol.StoreRequest(info, new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return projectFilesystem.newFileInputStream(file);
        }
    });
    eventBuilder.getStoreBuilder().setRequestSizeBytes(storeRequest.getContentLength());
    // Wrap the file into a `RequestBody` which uses `ProjectFilesystem`.
    builder.put(new RequestBody() {

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

        @Override
        public long contentLength() throws IOException {
            return storeRequest.getContentLength();
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
            StoreWriteResult writeResult = storeRequest.write(bufferedSink.outputStream());
            eventBuilder.getStoreBuilder().setArtifactContentHash(writeResult.getArtifactContentHashCode().toString());
        }
    });
    // Dispatch the store operation and verify it succeeded.
    try (HttpResponse response = storeClient.makeRequest("/artifacts/key", builder)) {
        final boolean requestFailed = response.statusCode() != HttpURLConnection.HTTP_ACCEPTED;
        if (requestFailed) {
            reportFailure("store(%s, %s): unexpected response: [%d:%s].", response.requestUrl(), info.getRuleKeys(), response.statusCode(), response.statusMessage());
        }
        eventBuilder.getStoreBuilder().setWasStoreSuccessful(!requestFailed);
    }
}
Also used : DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) Request(okhttp3.Request) HttpResponse(com.facebook.buck.slb.HttpResponse) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) ByteSource(com.google.common.io.ByteSource) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 2 with MediaType

use of okhttp3.MediaType in project okhttputils by hongyangAndroid.

the class LoggerInterceptor method logForResponse.

private Response logForResponse(Response response) {
    try {
        //===>response log
        Log.e(tag, "========response'log=======");
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        Log.e(tag, "url : " + clone.request().url());
        Log.e(tag, "code : " + clone.code());
        Log.e(tag, "protocol : " + clone.protocol());
        if (!TextUtils.isEmpty(clone.message()))
            Log.e(tag, "message : " + clone.message());
        if (showResponse) {
            ResponseBody body = clone.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    Log.e(tag, "responseBody's contentType : " + mediaType.toString());
                    if (isText(mediaType)) {
                        String resp = body.string();
                        Log.e(tag, "responseBody's content : " + resp);
                        body = ResponseBody.create(mediaType, resp);
                        return response.newBuilder().body(body).build();
                    } else {
                        Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }
        }
        Log.e(tag, "========response'log=======end");
    } catch (Exception e) {
    //            e.printStackTrace();
    }
    return response;
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 3 with MediaType

use of okhttp3.MediaType in project Rocket.Chat.Android by RocketChat.

the class FileUploadingWithUfsObserver method onUpdateResults.

@Override
public void onUpdateResults(List<FileUploading> results) {
    if (results.isEmpty()) {
        return;
    }
    List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm -> realm.where(FileUploading.class).equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING).findAll());
    if (uploadingList.size() >= 1) {
        // do not upload multiple files simultaneously
        return;
    }
    RealmUser currentUser = realmHelper.executeTransactionForRead(realm -> RealmUser.queryCurrentUser(realm).findFirst());
    RealmSession session = realmHelper.executeTransactionForRead(realm -> RealmSession.queryDefaultSession(realm).findFirst());
    if (currentUser == null || session == null) {
        return;
    }
    final String cookie = String.format("rc_uid=%s; rc_token=%s", currentUser.getId(), session.getToken());
    FileUploading fileUploading = results.get(0);
    final String roomId = fileUploading.getRoomId();
    final String uplId = fileUploading.getUplId();
    final String filename = fileUploading.getFilename();
    final long filesize = fileUploading.getFilesize();
    final String mimeType = fileUploading.getMimeType();
    final Uri fileUri = Uri.parse(fileUploading.getUri());
    final String store = FileUploading.STORAGE_TYPE_GRID_FS.equals(fileUploading.getStorageType()) ? "rocketchat_uploads" : (FileUploading.STORAGE_TYPE_FILE_SYSTEM.equals(fileUploading.getStorageType()) ? "fileSystem" : null);
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(_task -> methodCall.ufsCreate(filename, filesize, mimeType, store, roomId)).onSuccessTask(task -> {
        final JSONObject info = task.getResult();
        final String fileId = info.getString("fileId");
        final String token = info.getString("token");
        final String url = info.getString("url");
        final int bufSize = 16384;
        final byte[] buffer = new byte[bufSize];
        int offset = 0;
        final MediaType contentType = MediaType.parse(mimeType);
        try (InputStream inputStream = context.getContentResolver().openInputStream(fileUri)) {
            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                offset += read;
                double progress = 1.0 * offset / filesize;
                Request request = new Request.Builder().url(url + "&progress=" + progress).header("Cookie", cookie).post(RequestBody.create(contentType, buffer, 0, read)).build();
                Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
                if (response.isSuccessful()) {
                    final JSONObject obj = new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.UPLOADED_SIZE, offset);
                    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, obj));
                } else {
                    return Task.forError(new Exception(response.message()));
                }
            }
        }
        return methodCall.ufsComplete(fileId, token, store);
    }).onSuccessTask(task -> methodCall.sendFileMessage(roomId, null, task.getResult())).onSuccessTask(task -> realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCED).put(FileUploading.ERROR, JSONObject.NULL)))).continueWithTask(task -> {
        if (task.isFaulted()) {
            RCLog.w(task.getError());
            return realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.FAILED).put(FileUploading.ERROR, task.getError().getMessage())));
        } else {
            return Task.forResult(null);
        }
    });
}
Also used : Context(android.content.Context) Realm(io.realm.Realm) Request(okhttp3.Request) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) RealmResults(io.realm.RealmResults) Uri(android.net.Uri) RCLog(chat.rocket.android.log.RCLog) LogIfError(chat.rocket.android.helper.LogIfError) RequestBody(okhttp3.RequestBody) List(java.util.List) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) Response(okhttp3.Response) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) DDPClientRef(chat.rocket.android.service.DDPClientRef) Task(bolts.Task) OkHttpHelper(chat.rocket.android.helper.OkHttpHelper) MediaType(okhttp3.MediaType) InputStream(java.io.InputStream) FileUploadingHelper(chat.rocket.android.api.FileUploadingHelper) InputStream(java.io.InputStream) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) Request(okhttp3.Request) Uri(android.net.Uri) Response(okhttp3.Response) JSONObject(org.json.JSONObject) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) MediaType(okhttp3.MediaType) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession)

Example 4 with MediaType

use of okhttp3.MediaType in project MVPArms by JessYanCoding.

the class RequestIntercept method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (//在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不做操作则返回参数中的request
    mHandler != null)
        request = mHandler.onHttpRequestBefore(chain, request);
    Buffer requestbuffer = new Buffer();
    if (request.body() != null) {
        request.body().writeTo(requestbuffer);
    } else {
        Timber.tag("Request").w("request.body() == null");
    }
    //打印url信息
    Timber.tag("Request").w("Sending Request %s on %n Params --->  %s%n Connection ---> %s%n Headers ---> %s", request.url(), request.body() != null ? parseParams(request.body(), requestbuffer) : "null", chain.connection(), request.headers());
    long t1 = System.nanoTime();
    Response originalResponse = chain.proceed(request);
    long t2 = System.nanoTime();
    //打印响应时间
    Timber.tag("Response").w("Received response  in %.1fms%n%s", (t2 - t1) / 1e6d, originalResponse.headers());
    //读取服务器返回的结果
    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    // Buffer the entire body.
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    //获取content的压缩类型
    String encoding = originalResponse.headers().get("Content-Encoding");
    Buffer clone = buffer.clone();
    String bodyString;
    //解析response content
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        //content使用gzip压缩
        //解压
        bodyString = ZipHelper.decompressForGzip(clone.readByteArray());
    } else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {
        //content使用zlib压缩
        //解压
        bodyString = ZipHelper.decompressToStringForZlib(clone.readByteArray());
    } else {
        //content没有被压缩
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        bodyString = clone.readString(charset);
    }
    Timber.tag("Result").w(jsonFormat(bodyString));
    if (//这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
    mHandler != null)
        return mHandler.onHttpResultResponse(bodyString, chain, originalResponse);
    return originalResponse;
}
Also used : Buffer(okio.Buffer) Response(okhttp3.Response) Request(okhttp3.Request) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 5 with MediaType

use of okhttp3.MediaType in project ignite by apache.

the class RestExecutor method sendRequest.

/** */
private RestResult sendRequest(boolean demo, String path, Map<String, Object> params, String mtd, Map<String, Object> headers, String body) throws IOException {
    if (demo && AgentClusterDemo.getDemoUrl() == null) {
        try {
            AgentClusterDemo.tryStart().await();
        } catch (InterruptedException ignore) {
            throw new IllegalStateException("Failed to execute request because of embedded node for demo mode is not started yet.");
        }
    }
    String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    if (path != null)
        urlBuilder.addPathSegment(path);
    final Request.Builder reqBuilder = new Request.Builder();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
            reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
    }
    if ("GET".equalsIgnoreCase(mtd)) {
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null)
                    urlBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
            }
        }
    } else if ("POST".equalsIgnoreCase(mtd)) {
        if (body != null) {
            MediaType contentType = MediaType.parse("text/plain");
            reqBuilder.post(RequestBody.create(contentType, body));
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if (entry.getValue() != null)
                        formBody.add(entry.getKey(), entry.getValue().toString());
                }
            }
            reqBuilder.post(formBody.build());
        }
    } else
        throw new IllegalArgumentException("Unknown HTTP-method: " + mtd);
    reqBuilder.url(urlBuilder.build());
    try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
        String content = resp.body().string();
        if (resp.isSuccessful()) {
            JsonNode node = mapper.readTree(content);
            int status = node.get("successStatus").asInt();
            switch(status) {
                case STATUS_SUCCESS:
                    return RestResult.success(node.get("response").toString());
                default:
                    return RestResult.fail(status, node.get("error").asText());
            }
        }
        if (resp.code() == 401)
            return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in grid. Please check agent\'s login and password or node port.");
        return RestResult.fail(STATUS_FAILED, "Failed connect to node and execute REST command.");
    } catch (ConnectException ignore) {
        throw new ConnectException("Failed connect to node and execute REST command [url=" + urlBuilder + "]");
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) ConnectException(java.net.ConnectException)

Aggregations

MediaType (okhttp3.MediaType)97 RequestBody (okhttp3.RequestBody)84 Request (okhttp3.Request)80 Response (okhttp3.Response)72 IOException (java.io.IOException)67 ResponseBody (okhttp3.ResponseBody)35 Buffer (okio.Buffer)30 BufferedSink (okio.BufferedSink)28 Charset (java.nio.charset.Charset)25 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)16 OkHttpClient (okhttp3.OkHttpClient)13 InputStream (java.io.InputStream)11 HashMap (java.util.HashMap)11 MultipartBody (okhttp3.MultipartBody)11 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 List (java.util.List)9 Connection (okhttp3.Connection)9