Search in sources :

Example 31 with RequestBody

use of com.squareup.okhttp.RequestBody in project ButterRemote-Android by se-bastiaan.

the class PopcornTimeRpcClient method request.

/**
 * Send JSON RPC request to the instance
 * @param rpc Request data
 * @param callback Callback for the request
 * @return ResponseFuture
 */
private Call request(final RpcRequest rpc, final Callback callback) {
    RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, mGson.toJson(rpc));
    Request request = new Request.Builder().url(mUrl).header("Authorization", Credentials.basic(mUsername, mPassword)).post(requestBody).build();
    Call call = mClient.newCall(request);
    call.enqueue(new com.squareup.okhttp.Callback() {

        @Override
        public void onFailure(Request request, IOException e) {
            callback.onCompleted(e, null);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            RpcResponse result = null;
            Exception e = null;
            try {
                if (response != null && response.isSuccessful()) {
                    String responseStr = response.body().string();
                    // LogUtils.d("PopcornTimeRpcClient", "Response: " + responseStr);
                    result = mGson.fromJson(responseStr, RpcResponse.class);
                    LinkedTreeMap<String, Object> map = result.getMapResult();
                    if (map.containsKey("popcornVersion")) {
                        mVersion = (String) map.get("popcornVersion");
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                e = ex;
                mVersion = ZERO_VERSION;
                if (rpc.id == RequestId.GET_SELECTION.ordinal()) {
                    mVersion = "0.3.4";
                }
            }
            callback.onCompleted(e, result);
        }
    });
    return call;
}
Also used : Call(com.squareup.okhttp.Call) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) Request(com.squareup.okhttp.Request) Callback(com.squareup.okhttp.Callback) IOException(java.io.IOException) IOException(java.io.IOException) Response(com.squareup.okhttp.Response) RequestBody(com.squareup.okhttp.RequestBody)

Example 32 with RequestBody

use of com.squareup.okhttp.RequestBody in project android-rest-client by darko1002001.

the class RequestBodyUtils method create.

public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
    return new RequestBody() {

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

        @Override
        public long contentLength() {
            try {
                return inputStream.available();
            } catch (IOException e) {
                return 0;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = null;
            try {
                source = Okio.source(inputStream);
                sink.writeAll(source);
            } finally {
                Util.closeQuietly(source);
            }
        }
    };
}
Also used : BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Source(okio.Source) RequestBody(com.squareup.okhttp.RequestBody)

Example 33 with RequestBody

use of com.squareup.okhttp.RequestBody in project jesos by groupon.

the class HttpProtocolSender method sendHttpMessage.

public void sendHttpMessage(final UPID recipient, final Message message) throws IOException {
    if (closed.get()) {
        return;
    }
    checkNotNull(recipient, "recipient is null");
    checkNotNull(message, "message is null");
    checkArgument(recipient.getHost() != null, "%s is not a valid recipient for %s", recipient, message);
    checkArgument(recipient.getPort() > 0, "%s is not a valid recipient for %s", recipient, message);
    final String path = format("/%s/%s", recipient.getId(), message.getDescriptorForType().getFullName());
    final URL url = new URL("http", recipient.getHost(), recipient.getPort(), path);
    final UUID tag = UUID.randomUUID();
    inFlight.put(tag, SettableFuture.<Void>create());
    final RequestBody body = RequestBody.create(PROTOBUF_MEDIATYPE, message.toByteArray());
    final Request request = new Request.Builder().header("Libprocess-From", sender).url(url).post(body).tag(tag).build();
    LOG.debug("Sending from %s to URL %s: %s", sender, url, message);
    client.newCall(request).enqueue(this);
}
Also used : Request(com.squareup.okhttp.Request) UUID(java.util.UUID) URL(java.net.URL) RequestBody(com.squareup.okhttp.RequestBody)

Example 34 with RequestBody

use of com.squareup.okhttp.RequestBody in project xDrip by NightscoutFoundation.

the class LanguageEditor method uploadData.

private void uploadData(String data) {
    if (data.length() < 10) {
        // don't translate
        toast("No text entered - cannot send blank");
        return;
    }
    final String email = LanguageStore.getString(EMAIL_KEY);
    final String name = LanguageStore.getString(NAME_KEY);
    final String consent = LanguageStore.getString(CONSENT_KEY);
    if (email.length() == 0) {
        // don't translate
        toast("No email address stored - cannot send");
        return;
    }
    if (name.length() == 0) {
        // don't translate
        toast("No thanks name stored - cannot send");
        return;
    }
    if (consent.length() == 0) {
        // don't translate
        toast("No consent stored - cannot send");
        return;
    }
    final OkHttpClient client = new OkHttpClient();
    final String send_url = mContext.getString(R.string.wserviceurl) + "/joh-langdata";
    client.setConnectTimeout(20, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);
    // don't translate
    toast("Sending..");
    try {
        final RequestBody formBody = new FormEncodingBuilder().add("locale", Locale.getDefault().toString()).add("contact", email).add("name", name).add("consent", consent).add("data", data).build();
        new Thread(new Runnable() {

            public void run() {
                try {
                    final Request request = new Request.Builder().url(send_url).post(formBody).build();
                    Log.i(TAG, "Sending language data");
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        toast("data sent successfully");
                        ((Activity) mContext).runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    saveBtn.setVisibility(View.INVISIBLE);
                                    undoBtn.setVisibility(View.INVISIBLE);
                                } catch (Exception e) {
                                // do nothing if its gone away
                                }
                            }
                        });
                    } else {
                        toast("Error sending data: " + response.message());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Got exception in execute: " + e.toString());
                    // don't translate
                    toast("Error with network connection");
                }
            }
        }).start();
    } catch (Exception e) {
        toast(e.getMessage());
        Log.e(TAG, "General exception: " + e.toString());
    }
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) AppCompatActivity(android.support.v7.app.AppCompatActivity) BaseAppCompatActivity(com.eveningoutpost.dexdrip.BaseAppCompatActivity) Activity(android.app.Activity) RequestBody(com.squareup.okhttp.RequestBody)

Example 35 with RequestBody

use of com.squareup.okhttp.RequestBody in project xDrip by NightscoutFoundation.

the class DisplayQRCode method uploadBytes.

public static synchronized void uploadBytes(byte[] result, final int callback_option) {
    final PowerManager.WakeLock wl = JoH.getWakeLock("uploadBytes", 1200000);
    if ((result != null) && (result.length > 0)) {
        final byte[] mykey = CipherUtils.getRandomKey();
        byte[] crypted_data = CipherUtils.encryptBytes(JoH.compressBytesToBytes(result), mykey);
        if ((crypted_data != null) && (crypted_data.length > 0)) {
            Log.d(TAG, "Before: " + result.length + " After: " + crypted_data.length);
            final OkHttpClient client = new OkHttpClient();
            client.setConnectTimeout(15, TimeUnit.SECONDS);
            client.setReadTimeout(30, TimeUnit.SECONDS);
            client.setWriteTimeout(30, TimeUnit.SECONDS);
            toast("Preparing");
            try {
                send_url = xdrip.getAppContext().getString(R.string.wserviceurl) + "/joh-setsw";
                final String bbody = Base64.encodeToString(crypted_data, Base64.NO_WRAP);
                Log.d(TAG, "Upload Body size: " + bbody.length());
                final RequestBody formBody = new FormEncodingBuilder().add("data", bbody).build();
                new Thread(new Runnable() {

                    public void run() {
                        try {
                            final Request request = new Request.Builder().header("User-Agent", "Mozilla/5.0 (jamorham)").header("Connection", "close").url(send_url).post(formBody).build();
                            Log.i(TAG, "Uploading data");
                            Response response = client.newCall(request).execute();
                            if (response.isSuccessful()) {
                                final String reply = response.body().string();
                                Log.d(TAG, "Got success response length: " + reply.length() + " " + reply);
                                if ((reply.length() == 35) && (reply.startsWith("ID:"))) {
                                    switch(callback_option) {
                                        case 1:
                                            {
                                                if (mInstance != null) {
                                                    mInstance.display_final_all_settings_qr_code(reply.substring(3, 35), mykey);
                                                } else {
                                                    Log.e(TAG, "mInstance null");
                                                }
                                                break;
                                            }
                                        case 2:
                                            {
                                                GcmActivity.backfillLink(reply.substring(3, 35), JoH.bytesToHex(mykey));
                                                break;
                                            }
                                        default:
                                            {
                                                toast("Invalid callback option on upload");
                                            }
                                    }
                                } else {
                                    Log.d(TAG, "Got unhandled reply: " + reply);
                                    toast(reply);
                                }
                            } else {
                                toast("Error please try again");
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "Got exception in execute: " + e.toString());
                            e.printStackTrace();
                            toast("Error with connection");
                        }
                    }
                }).start();
            } catch (Exception e) {
                toast(e.getMessage());
                Log.e(TAG, "General exception: " + e.toString());
            } finally {
                JoH.releaseWakeLock(wl);
            }
        } else {
            toast("Something went wrong preparing the settings");
        }
    } else {
        toast("Could not read data somewhere");
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) PowerManager(android.os.PowerManager) Response(com.squareup.okhttp.Response) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

RequestBody (com.squareup.okhttp.RequestBody)39 Request (com.squareup.okhttp.Request)33 Response (com.squareup.okhttp.Response)24 IOException (java.io.IOException)19 OkHttpClient (com.squareup.okhttp.OkHttpClient)14 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)12 BufferedSink (okio.BufferedSink)7 MultipartBuilder (com.squareup.okhttp.MultipartBuilder)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 Call (com.squareup.okhttp.Call)3 Buffer (okio.Buffer)3 Activity (android.app.Activity)2 PowerManager (android.os.PowerManager)2 AppCompatActivity (android.support.v7.app.AppCompatActivity)2 EditText (android.widget.EditText)2 BaseAppCompatActivity (com.eveningoutpost.dexdrip.BaseAppCompatActivity)2 MediaType (com.squareup.okhttp.MediaType)2 CookieManager (java.net.CookieManager)2 GzipSink (okio.GzipSink)2 ApiCallException (org.eyeseetea.malariacare.domain.exception.ApiCallException)2