Example usage for com.squareup.okhttp RequestBody create

List of usage examples for com.squareup.okhttp RequestBody create

Introduction

In this page you can find the example usage for com.squareup.okhttp RequestBody create.

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public int performCreateFeedRequest(HttpUrl url, String feedUrlString, long folderId) throws Exception {
    HttpUrl feedUrl = url.newBuilder().setQueryParameter("url", feedUrlString)
            .setQueryParameter("folderId", String.valueOf(folderId)).build();

    Request request = new Request.Builder().url(feedUrl).post(RequestBody.create(JSON, "")).build();

    Response response = client.newCall(request).execute();

    return response.code();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public int performRenameFeedRequest(HttpUrl url, long feedId, String newFeedName) throws Exception {
    HttpUrl feedUrl = url.newBuilder().addPathSegment(String.valueOf(feedId)).addPathSegment("rename").build();

    Request request = new Request.Builder().url(feedUrl)
            .put(RequestBody.create(JSON, new JSONObject().put("feedTitle", newFeedName).toString())).build();

    Response response = client.newCall(request).execute();

    return response.code();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public int performTagChangeRequest(HttpUrl url, String content) throws Exception {
    Request request = new Request.Builder().url(url).put(RequestBody.create(JSON, content)).build();

    Response response = client.newCall(request).execute();

    return response.code();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public Tuple<Integer, String> performCreateFolderRequest(HttpUrl url, String folderName) throws Exception {
    Request request = new Request.Builder().url(url)
            .post(RequestBody.create(JSON, new JSONObject().put("name", folderName).toString())).build();

    Response response = client.newCall(request).execute();
    String body = response.body().string();
    return new Tuple<>(response.code(), body);
}

From source file:com.ringcentral.rc_android_sdk.rcsdk.utils.Helpers.java

License:Open Source License

/**
     * sendSMS Helper// w  w  w  . ja  v a2 s. com
     * @param to
     * @param from
     * @param message
     * @param callback
     */
    public void sendSMS(String to, String from, String message, APICallback callback) {

        String payload = "{\"to\": [{\"phoneNumber\":\" " + to + "\"}]," + "\"from\": {\"phoneNumber\":\" " + from
                + "\"}," + "\"text\":\"" + message + "\"}";

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), payload.getBytes());

        try {
            platform.post(API.SMS.value, body, null, callback);
        } catch (AuthException e) {
            e.printStackTrace();
        }

    }

From source file:com.sannniu.ncore.http.GsonRequestBodyConverter.java

License:Apache License

@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    try {//from  w  w w  .  ja  v  a2  s. com
        gson.toJson(value, type, writer);
        writer.flush();
    } catch (IOException e) {
        throw new AssertionError(e); // Writing to Buffer does no I/O.
    }
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}

From source file:com.secupwn.aimsicd.utils.RequestTask.java

@Override
protected String doInBackground(String... commandString) {

    // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
    switch (mType) {
    // OCID upload request from "APPLICATION" drawer title
    case DBE_UPLOAD_REQUEST:
        try {// ww w .j  ava  2s .  c  om
            @Cleanup
            Realm realm = Realm.getDefaultInstance();
            boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);

            log.info("OCID upload data prepared - " + String.valueOf(prepared));
            if (prepared) {
                File file = new File((mAppContext.getExternalFilesDir(null) + File.separator)
                        + "OpenCellID/aimsicd-ocid-data.csv");
                publishProgress(25, 100);

                RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                        .addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile",
                                "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file))
                        .build();

                Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv")
                        .post(requestBody).build();

                publishProgress(60, 100);

                Response response = okHttpClient.newCall(request).execute();

                publishProgress(80, 100);
                if (response != null) {
                    log.info("OCID Upload Response: " + response.code() + " - " + response.message());
                    if (response.code() == 200) {
                        Realm.Transaction transaction = mDbAdapter.ocidProcessed();
                        realm.executeTransaction(transaction);
                    }
                    publishProgress(95, 100);
                }
                return "Successful";
            } else {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
                return null;
            }

            // all caused by httpclient.execute(httppost);
        } catch (UnsupportedEncodingException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (FileNotFoundException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (IOException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (Exception e) {
            log.error("Upload OpenCellID data Exception", e);
        }

        // DOWNLOADING...
    case DBE_DOWNLOAD_REQUEST: // OCID download request from "APPLICATION" drawer title
        mTimeOut = REQUEST_TIMEOUT_MENU;
    case DBE_DOWNLOAD_REQUEST_FROM_MAP: // OCID download request from "Antenna Map Viewer"
        int count;
        try {
            long total;
            int progress = 0;
            String dirName = getOCDBDownloadDirectoryPath(mAppContext);
            File dir = new File(dirName);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, OCDB_File_Name);
            log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);

            Request request = new Request.Builder().url(commandString[0]).get().build();

            Response response;
            try {
                // OCID's API can be slow. Give it up to a minute to do its job. Since this
                // is a backgrounded task, it's ok to wait for a while.
                okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
                response = okHttpClient.newCall(request).execute();
                okHttpClient.setReadTimeout(10, TimeUnit.SECONDS); // Restore back to default
            } catch (SocketTimeoutException e) {
                log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
                return "Timeout";
            }

            if (response.code() != 200) {
                try {
                    String error = response.body().string();
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
                    log.error("Download OCID data error: " + error);
                } catch (Exception e) {
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " "
                            + e.getClass().getName() + " - " + e.getMessage());
                    log.error("Download OCID exception: ", e);
                }
                return "Error";
            } else {
                // This returns "-1" for streamed response (Chunked Transfer Encoding)
                total = response.body().contentLength();
                if (total == -1) {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
                    total = 1024; // Let's set it arbitrarily to something other than "-1"
                } else {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                    publishProgress((int) (0.25 * total), (int) total); // Let's show something!
                }

                FileOutputStream output = new FileOutputStream(file, false);
                InputStream input = new BufferedInputStream(response.body().byteStream());

                byte[] data = new byte[1024];
                while ((count = input.read(data)) > 0) {
                    // writing data to file
                    output.write(data, 0, count);
                    progress += count;
                    publishProgress(progress, (int) total);
                }
                input.close();
                // flushing output
                output.flush();
                output.close();
            }
            return "Successful";

        } catch (IOException e) {
            log.warn("Problem reading data from steam", e);
            return null;
        }
    }

    return null;
}

From source file:com.shadowmaps.example.service.ShadowMapsService.java

License:Apache License

private void postUpdate(final OutgoingInfo packet) {
    new AsyncTask<Void, Void, Void>() {

        @Override// w  w w.  j  av a 2  s  . c  o  m
        protected Void doInBackground(Void... params) {
            try {
                String toSend = objectMapper.writeValueAsString(packet);
                RequestBody body = RequestBody.create(JSON, toSend);
                Request request = new Request.Builder().url(URL_TO_POST).post(body).build();
                Response response = client.newCall(request).execute();
                String response_str = response.body().string();
                Log.v(TAG, String.format("Received ShadowMapsUpdate: %s", response_str));
                if (response.code() == 200) {
                    Log.v("HTTP", "200!");
                    try {
                        Intent intent = new Intent();
                        long time_processed = System.currentTimeMillis();
                        ServerResponse message = objectMapper.readValue(response_str, ServerResponse.class);
                        Log.v("Server JSON", "Got Message");
                        double lon = message.getDeviceInfo().getLon();
                        double lat = message.getDeviceInfo().getLat();
                        double acc = message.getDeviceInfo().getAcc();
                        if (message.getRouteInfo() != null) {
                            double route_lon = message.getRouteInfo().getLongitude();
                            double route_lat = message.getRouteInfo().getLatitude();
                            double route_acc = message.getRouteInfo().getAccuracyHoriz();
                            intent.putExtra("clamp_lat", route_lat);
                            intent.putExtra("clamp_lon", route_lon);
                            intent.putExtra("clamp_radius", route_acc);
                            intent.putExtra("street", message.getRouteInfo().getStreetName());
                        }
                        Log.v("ShadowMaps", "Location Update received.");
                        intent.setAction("shadowmaps.location.update");
                        intent.putExtra("lat", lat);
                        intent.putExtra("lon", lon);
                        intent.putExtra("radius", acc);
                        intent.putExtra("orig_lat", packet.getDev().getLat());
                        intent.putExtra("orig_lon", packet.getDev().getLon());
                        intent.putExtra("orig_acc", packet.getDev().getAcc());

                        Log.v("ShadowMaps", String.format("Lat/Lon: %s,%s. Radius:%s", lat, lon, acc));
                        sendBroadcast(intent);
                        return null;
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.v("Exception", e.getMessage());
                    }
                } else {
                    Log.v("HTTP", "" + response.code());

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }.execute();
}

From source file:com.shopify.buy.dataprovider.BuyClient.java

License:Open Source License

/**
 * Post a credit card to Shopify's card server and associate it with a Checkout
 *
 * @param card     the {@link CreditCard} to associate
 * @param checkout the {@link Checkout} to associate the card with
 * @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
 *//*from   w  w  w.  j ava 2  s . c  om*/
public void storeCreditCard(final CreditCard card, final Checkout checkout, final Callback<Checkout> callback) {
    if (card == null) {
        throw new NullPointerException("card cannot be null");
    }

    if (checkout == null) {
        throw new NullPointerException("checkout cannot be null");
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            PaymentSessionCheckoutWrapper dataWrapper = new PaymentSessionCheckoutWrapper();
            PaymentSessionCheckout data = new PaymentSessionCheckout();
            data.setToken(checkout.getToken());
            data.setCreditCard(card);
            data.setBillingAddress(checkout.getBillingAddress());
            dataWrapper.setCheckout(data);

            RequestBody body = RequestBody.create(jsonMediateType, new Gson().toJson(dataWrapper));

            Request request = new Request.Builder().url(checkout.getPaymentUrl()).post(body)
                    .addHeader("Authorization",
                            "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.NO_WRAP))
                    .addHeader("Content-Type", "application/json").addHeader("Accept", "application/json")
                    .build();
            try {
                com.squareup.okhttp.Response httpResponse = httpClient.newCall(request).execute();
                String paymentSessionId = parsePaymentSessionResponse(httpResponse);
                checkout.setPaymentSessionId(paymentSessionId);

                Response retrofitResponse = new Response(request.urlString(), httpResponse.code(),
                        httpResponse.message(), Collections.<Header>emptyList(), null);
                callback.success(checkout, retrofitResponse);
            } catch (IOException e) {
                e.printStackTrace();

                callback.failure(RetrofitError.unexpectedError(request.urlString(), e));
            }
        }
    }).start();
}

From source file:com.sitexa.android.data.net.okhttp.OkHttpApi.java

License:Apache License

@NonNull
public OkHttpApi postRequest(String doAction, Map<String, String> requestParam) {
    try {/*w  ww  .  j  a  va 2 s.  c o m*/
        String uri = getUrlString(doAction);
        this.url = new URL(uri);
        String params = getPostMethodParams(requestParam);
        this.requestBody = RequestBody.create(JSON, params);
        return this;
    } catch (Exception e) {
        Log.d(TAG, e.getMessage());
        throw new RuntimeException(new NetworkConnectionException(e.getMessage()));
    }
}