Search in sources :

Example 41 with Builder

use of okhttp3.MultipartBody.Builder in project HL4A by HL4A.

the class PaasClient method postBatchObject.

// only called @sendPendingOps
public void postBatchObject(List<Object> parameters, boolean sync, Map<String, String> header, GenericObjectCallback callback) {
    try {
        String url = batchUrl();
        Map<String, Object> requests = batchRequest(parameters);
        String json = JSON.toJSONString(requests);
        ByteArrayEntity entity = new ByteArrayEntity(json.getBytes(DEFAULT_ENCODING));
        if (AVOSCloud.isDebugLogEnabled()) {
            dumpHttpPostRequest(header, url, json);
        }
        AsyncHttpResponseHandler handler = createPostHandler(callback);
        AVHttpClient client = AVHttpClient.clientInstance();
        Request.Builder builder = new Request.Builder();
        builder.url(url).post(RequestBody.create(AVHttpClient.JSON, json));
        updateHeaders(builder, header, callback != null && callback.isRequestStatisticNeed());
        client.execute(builder.build(), sync, handler);
    } catch (Exception exception) {
        processException(exception, callback);
    }
}
Also used : ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Request(okhttp3.Request)

Example 42 with Builder

use of okhttp3.MultipartBody.Builder in project HL4A by HL4A.

the class PaasClient method postBatchSave.

public void postBatchSave(final List list, final boolean sync, final boolean isEventually, final Map<String, String> header, final GenericObjectCallback callback, final String objectId, final String _internalId) {
    try {
        Map params = new HashMap();
        params.put("requests", list);
        String paramString = AVUtils.jsonStringFromMapWithNull(params);
        if (isEventually) {
            File archivedFile = archiveRequest("post", batchSaveRelativeUrl(), paramString, objectId, _internalId);
            handleArchivedRequest(archivedFile, sync, callback);
        } else {
            String url = buildUrl(batchSaveRelativeUrl());
            if (AVOSCloud.isDebugLogEnabled()) {
                dumpHttpPostRequest(header, url, paramString);
            }
            AsyncHttpResponseHandler handler = createPostHandler(callback);
            AVHttpClient client = AVHttpClient.clientInstance();
            Request.Builder builder = new Request.Builder();
            builder.url(url).post(RequestBody.create(AVHttpClient.JSON, paramString));
            updateHeaders(builder, header, callback != null && callback.isRequestStatisticNeed());
            client.execute(builder.build(), sync, handler);
        }
    } catch (Exception exception) {
        processException(exception, callback);
    }
}
Also used : HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) Request(okhttp3.Request) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap) File(java.io.File)

Example 43 with Builder

use of okhttp3.MultipartBody.Builder in project HL4A by HL4A.

the class PaasClient method deleteObject.

public void deleteObject(final String relativePath, boolean sync, boolean isEventually, GenericObjectCallback callback, String objectId, String _internalId) {
    try {
        if (isEventually) {
            File archivedFile = archiveRequest("delete", relativePath, null, objectId, _internalId);
            handleArchivedRequest(archivedFile, sync, callback);
        } else {
            String url = buildUrl(relativePath);
            if (AVOSCloud.isDebugLogEnabled()) {
                dumpHttpDeleteRequest(null, url, null);
            }
            AsyncHttpResponseHandler handler = createPostHandler(callback);
            AVHttpClient client = AVHttpClient.clientInstance();
            Request.Builder builder = new Request.Builder();
            updateHeaders(builder, null, callback != null && callback.isRequestStatisticNeed());
            builder.url(url).delete();
            client.execute(builder.build(), sync, handler);
        }
    } catch (Exception exception) {
        processException(exception, callback);
    }
}
Also used : Request(okhttp3.Request) File(java.io.File)

Example 44 with Builder

use of okhttp3.MultipartBody.Builder 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)

Example 45 with Builder

use of okhttp3.MultipartBody.Builder in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClientTest method testGetOkHttpRequestType.

// region testTransferRequest/Response
@Test
public void testGetOkHttpRequestType() throws IOException {
    ParseHttpClient parseClient = ParseHttpClient.createClient(new OkHttpClient.Builder());
    ParseHttpRequest.Builder builder = new ParseHttpRequest.Builder();
    builder.setUrl("http://www.parse.com");
    // Get
    ParseHttpRequest parseRequest = builder.setMethod(ParseHttpRequest.Method.GET).setBody(null).build();
    Request okHttpRequest = parseClient.getRequest(parseRequest);
    assertEquals(ParseHttpRequest.Method.GET.toString(), okHttpRequest.method());
    // Post
    parseRequest = builder.setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody("test", "application/json")).build();
    okHttpRequest = parseClient.getRequest(parseRequest);
    assertEquals(ParseHttpRequest.Method.POST.toString(), okHttpRequest.method());
    // Delete
    parseRequest = builder.setMethod(ParseHttpRequest.Method.DELETE).setBody(null).build();
    okHttpRequest = parseClient.getRequest(parseRequest);
    assertEquals(ParseHttpRequest.Method.DELETE.toString(), okHttpRequest.method());
    assertNull(okHttpRequest.body());
    // Put
    parseRequest = builder.setMethod(ParseHttpRequest.Method.PUT).setBody(new ParseByteArrayHttpBody("test", "application/json")).build();
    okHttpRequest = parseClient.getRequest(parseRequest);
    assertEquals(ParseHttpRequest.Method.PUT.toString(), okHttpRequest.method());
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) Test(org.junit.Test)

Aggregations

Request (okhttp3.Request)412 OkHttpClient (okhttp3.OkHttpClient)360 Response (okhttp3.Response)287 IOException (java.io.IOException)221 RequestBody (okhttp3.RequestBody)173 HttpUrl (okhttp3.HttpUrl)109 MultipartBody (okhttp3.MultipartBody)102 File (java.io.File)93 Map (java.util.Map)92 Test (org.junit.Test)92 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)87 Call (okhttp3.Call)77 HashMap (java.util.HashMap)64 AndroidFlipperClient (com.facebook.flipper.android.AndroidFlipperClient)59 FlipperClient (com.facebook.flipper.core.FlipperClient)59 DatabasesFlipperPlugin (com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin)59 FrescoFlipperPlugin (com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin)59 InspectorFlipperPlugin (com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin)59 NetworkFlipperPlugin (com.facebook.flipper.plugins.network.NetworkFlipperPlugin)59 ReactFlipperPlugin (com.facebook.flipper.plugins.react.ReactFlipperPlugin)59