Search in sources :

Example 96 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project ignite by apache.

the class RestExecutor method sendRequest0.

/**
 */
private RestResult sendRequest0(String nodeUrl, boolean demo, String path, Map<String, Object> params, 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 send request because of embedded node for demo mode is not started yet.");
        }
    }
    String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
    HttpUrl httpUrl = HttpUrl.parse(url);
    if (httpUrl == null)
        throw new IllegalStateException("Failed to send request because of node URL is invalid: " + url);
    HttpUrl.Builder urlBuilder = httpUrl.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 (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());
    }
    reqBuilder.url(urlBuilder.build());
    try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
        if (resp.isSuccessful()) {
            RestResponseHolder res = MAPPER.readValue(resp.body().byteStream(), RestResponseHolder.class);
            int status = res.getSuccessStatus();
            switch(status) {
                case STATUS_SUCCESS:
                    return RestResult.success(res.getResponse());
                default:
                    return RestResult.fail(status, res.getError());
            }
        }
        if (resp.code() == 401)
            return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in cluster. " + "Please check agent\'s login and password or node port.");
        if (resp.code() == 404)
            return RestResult.fail(STATUS_FAILED, "Failed connect to cluster.");
        return RestResult.fail(STATUS_FAILED, "Failed to execute REST command: " + resp.message());
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 97 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project Fast-Android-Networking by amitshekhariitbhu.

the class HttpLoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
            }
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpHeaders.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 98 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project HL4A by HL4A.

the class QCloudUploader method uploadFile.

private void uploadFile() throws 后端错误 {
    try {
        if (AVOSCloud.showInternalDebugLog()) {
            LogUtil.log.d("upload as whole file");
        }
        byte[] bytes = avFile.getData();
        fileSha = AVUtils.SHA1(bytes);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody fileBody = RequestBody.create(MediaType.parse(APPLICATION_OCTET_STREAM), bytes, 0, getCurrentSliceLength(0, bytes.length));
        builder.addFormDataPart(FILE_CONTENT, fileKey, fileBody);
        builder.addFormDataPart(PARAM_OP, OP_UPLOAD);
        builder.addFormDataPart(PARAM_SHA, fileSha);
        MediaType type = MediaType.parse(MULTIPART_FORM_DATA);
        if (null != type) {
            builder.setType(type);
        }
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(uploadUrl);
        requestBuilder.header(HEADER_AUTHORIZATION, token);
        requestBuilder.header(HEADER_CONTENT_TYPE, MULTIPART_FORM_DATA);
        for (String key : FileUploader.UPLOAD_HEADERS.keySet()) {
            requestBuilder.header(key, FileUploader.UPLOAD_HEADERS.get(key));
        }
        requestBuilder.post(builder.build());
        Request request = requestBuilder.build();
        Response response = executeWithRetry(request, RETRY_TIMES);
        if (response.code() != 200) {
            throw AVErrorUtils.createException(后端错误.OTHER_CAUSE, AVUtils.stringFromBytes(response.body().bytes()));
        }
    } catch (Exception e) {
        if (AVOSCloud.isDebugLogEnabled()) {
            LogUtil.avlog.e("Exception during file upload", e);
        }
        throw AVErrorUtils.createException(e, "Exception during file upload");
    }
}
Also used : Response(okhttp3.Response) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 99 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project HL4A by HL4A.

the class QCloudUploader method uploadControlSlice.

private JSONObject uploadControlSlice(String token, String url, byte[] wholeFile) throws 后端错误 {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    try {
        String fileSha = AVUtils.SHA1(wholeFile);
        builder.addFormDataPart(PARAM_SHA, fileSha);
        builder.addFormDataPart(PARAM_OP, OP_UPLOAD_SLICE);
        builder.addFormDataPart(PARAM_FILE_SIZE, String.valueOf(wholeFile.length));
        builder.addFormDataPart(PARAM_SLICE_SIZE, String.valueOf(DEFAULT_SLICE_LEN));
        MediaType type = MediaType.parse(MULTIPART_FORM_DATA);
        if (null != type) {
            builder.setType(type);
        }
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url);
        requestBuilder.header(HEADER_AUTHORIZATION, token);
        requestBuilder.header(HEADER_CONTENT_TYPE, MULTIPART_FORM_DATA);
        requestBuilder.post(builder.build());
        Request request = requestBuilder.build();
        Response response = executeWithRetry(request, RETRY_TIMES);
        if (response != null) {
            byte[] responseBody = response.body().bytes();
            return parseSliceUploadResponse(AVUtils.stringFromBytes(responseBody));
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new 后端错误(后端错误.OTHER_CAUSE, "Upload file failure");
    }
    return null;
}
Also used : Response(okhttp3.Response) com.avos.avoscloud.后端错误(com.avos.avoscloud.后端错误) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) MediaType(okhttp3.MediaType)

Example 100 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project serverless by bluenimble.

the class HttpRemote method request.

private boolean request(ApiVerb verb, JsonObject spec, Callback callback, ApiStreamSource... attachments) {
    JsonObject rdata = Json.getObject(spec, Spec.Data);
    if (!Json.isNullOrEmpty(featureSpec)) {
        JsonObject master = featureSpec.duplicate();
        Json.resolve(master, ECompiler, new VariableResolver() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object resolve(String namespace, String... property) {
                Object v = Json.find(rdata, property);
                Json.remove(rdata, property);
                return v;
            }
        });
        spec = master.merge(spec);
    }
    String endpoint = Json.getString(spec, Spec.Endpoint);
    String path = Json.getString(spec, Spec.Path);
    if (!Lang.isNullOrEmpty(path)) {
        endpoint += path;
    }
    Serializer.Name serName = null;
    try {
        serName = Serializer.Name.valueOf(Json.getString(spec, Spec.Serializer, Serializer.Name.text.name()).toLowerCase());
    } catch (Exception ex) {
        // ignore
        serName = Serializer.Name.text;
    }
    Serializer serializer = Serializers.get(serName);
    Request request = null;
    Response response = null;
    try {
        // contentType
        String contentType = null;
        // resole and add headers
        JsonObject headers = Json.getObject(spec, Spec.Headers);
        if (!Json.isNullOrEmpty(headers)) {
            Json.resolve(headers, ECompiler, new VariableResolver() {

                private static final long serialVersionUID = 1L;

                @Override
                public Object resolve(String namespace, String... property) {
                    return Json.find(rdata, property);
                }
            });
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                if (HttpHeaders.CONTENT_TYPE.toUpperCase().equals(hn.toUpperCase())) {
                    contentType = hv;
                }
            }
        }
        if (Lang.isNullOrEmpty(contentType)) {
            contentType = ContentTypes.FormUrlEncoded;
        }
        contentType = contentType.trim();
        MediaType mediaType = MediaTypes.get(contentType);
        RequestBody body = null;
        List<RequestParameter> parameters = null;
        if (attachments != null && attachments.length > 0 && !Json.isNullOrEmpty(rdata)) {
            // multipart body
            MultipartBody.Builder builder = new MultipartBody.Builder();
            Iterator<String> pnames = rdata.keys();
            while (pnames.hasNext()) {
                String pn = pnames.next();
                builder.addFormDataPart(pn, String.valueOf(rdata.get(pn)));
            }
            for (ApiStreamSource ss : attachments) {
                try {
                    builder.addFormDataPart(ss.name(), ss.name(), RequestBody.create(MediaType.parse(contentType), IOUtils.toByteArray(ss.stream())));
                } catch (Exception ex) {
                    callback.onError(Error.Other, ex.getMessage());
                    return false;
                }
            }
        } else if (contentType.startsWith(ContentTypes.Json)) {
            body = RequestBody.create(mediaType, rdata == null ? JsonObject.EMPTY_OBJECT : rdata.toString());
        } else {
            if (!Json.isNullOrEmpty(rdata)) {
                // for bnb signature only
                if (Signers.Bnb.equals(Json.find(spec, Spec.Sign, Spec.SignProtocol))) {
                    parameters = new ArrayList<RequestParameter>();
                }
                if (verb.equals(ApiVerb.POST) || verb.equals(ApiVerb.PUT) || verb.equals(ApiVerb.PATCH)) {
                    FormBody.Builder fb = new FormBody.Builder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        fb.add(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    body = fb.build();
                } else if (verb.equals(ApiVerb.GET)) {
                    HttpUrl.Builder urlBuilder = HttpUrl.parse(endpoint).newBuilder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        urlBuilder.addQueryParameter(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    endpoint = urlBuilder.build().toString();
                }
            }
        }
        // create the request builder
        Request.Builder rBuilder = new Request.Builder().url(endpoint);
        rBuilder.header(HttpHeaders.USER_AGENT, DefaultUserAgent);
        // add headers
        if (!Json.isNullOrEmpty(headers)) {
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                rBuilder.header(hn, hv);
            }
        }
        // create request
        switch(verb) {
            case GET:
                rBuilder.get();
                break;
            case POST:
                rBuilder.post(body);
                break;
            case DELETE:
                rBuilder.delete();
                break;
            case PUT:
                rBuilder.put(body);
                break;
            case PATCH:
                rBuilder.patch(body);
                break;
            case HEAD:
                rBuilder.head();
                break;
            default:
                break;
        }
        // build then sign
        request = sign(rBuilder.build(), spec, parameters);
        response = http.newCall(request).execute();
        if (response.code() > Json.getInteger(spec, Spec.SuccessCode, 202)) {
            callback.onError(response.code(), response.body().string());
            return false;
        } else {
            callback.onSuccess(response.code(), serializer.serialize(response.body().byteStream()));
            return true;
        }
    } catch (UnknownHostException uhex) {
        callback.onError(Error.UnknownHost, "Endpoint " + endpoint + " can't be resolved. Check your internet connection and make sure the endpoint is correct");
        return false;
    } catch (SocketTimeoutException stoex) {
        callback.onError(Error.Timeout, "Endpoint " + endpoint + " was found but " + stoex.getMessage());
        return false;
    } catch (Exception ex) {
        callback.onError(Error.Other, Lang.toError(ex));
        return false;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(com.bluenimble.platform.json.JsonObject) Iterator(java.util.Iterator) MediaType(okhttp3.MediaType) TextSerializer(com.bluenimble.platform.remote.impls.serializers.TextSerializer) Serializer(com.bluenimble.platform.remote.Serializer) StreamSerializer(com.bluenimble.platform.remote.impls.serializers.StreamSerializer) JsonSerializer(com.bluenimble.platform.remote.impls.serializers.JsonSerializer) XmlSerializer(com.bluenimble.platform.remote.impls.serializers.XmlSerializer) RequestBody(okhttp3.RequestBody) UnknownHostException(java.net.UnknownHostException) Request(okhttp3.Request) FormBody(okhttp3.FormBody) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) SocketTimeoutException(java.net.SocketTimeoutException) MultipartBody(okhttp3.MultipartBody) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21