Search in sources :

Example 6 with RequestBody

use of com.squareup.okhttp.RequestBody in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class RequestTask method doInBackground.

@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 {
                @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 // OCID download request from "APPLICATION" drawer title
        DBE_DOWNLOAD_REQUEST:
            mTimeOut = REQUEST_TIMEOUT_MENU;
        case // OCID download request from "Antenna Map Viewer"
        DBE_DOWNLOAD_REQUEST_FROM_MAP:
            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();
                    // Restore back to default
                    okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
                } 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!");
                        // Let's set it arbitrarily to something other than "-1"
                        total = 1024;
                    } else {
                        log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                        // Let's show something!
                        publishProgress((int) (0.25 * total), (int) total);
                    }
                    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;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Cleanup(lombok.Cleanup) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.squareup.okhttp.Response) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) Realm(io.realm.Realm) File(java.io.File) RequestBody(com.squareup.okhttp.RequestBody)

Example 7 with RequestBody

use of com.squareup.okhttp.RequestBody in project ETSMobile-Android2 by ApplETS.

the class AuthentificationPortailTask method doInBackground.

protected Intent doInBackground(String... params) {
    OkHttpClient client = new OkHttpClient();
    String url = params[0], username = params[1], password = params[2];
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, "{\n  \"Username\": \"" + username + "\",\n  \"Password\": \"" + password + "\"\n}");
    Request request = new Request.Builder().url(url).post(body).addHeader("content-type", "application/json").addHeader("cache-control", "no-cache").build();
    Response response = null;
    String authCookie = "", domaine = "";
    int typeUsagerId = 0;
    final Intent res = new Intent();
    try {
        response = client.newCall(request).execute();
        if (response.code() == 200) {
            authCookie = response.header("Set-Cookie");
            JSONObject jsonResponse = new JSONObject(response.body().string());
            typeUsagerId = jsonResponse.getInt("TypeUsagerId");
            domaine = jsonResponse.getString("Domaine");
            res.putExtra(AccountManager.KEY_AUTHTOKEN, authCookie);
            res.putExtra(Constants.TYPE_USAGER_ID, typeUsagerId);
            res.putExtra(Constants.DOMAINE, domaine);
        } else {
            Log.e("Erreur Portail", response.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    res.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
    res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    res.putExtra(Constants.PARAM_USER_PASS, password);
    return res;
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) JSONObject(org.json.JSONObject) Request(com.squareup.okhttp.Request) MediaType(com.squareup.okhttp.MediaType) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Example 8 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 9 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 10 with RequestBody

use of com.squareup.okhttp.RequestBody in project Notes by lguipeng.

the class TAndroidTransport method flush.

@Override
public void flush() throws TTransportException {
    Util.closeQuietly(mResponseBody);
    mResponseBody = null;
    RequestBody requestBody = new RequestBody() {

        @Override
        public MediaType contentType() {
            if (mHeaders != null && mHeaders.containsKey("Content-Type")) {
                return MediaType.parse(mHeaders.get("Content-Type"));
            } else {
                return MEDIA_TYPE_THRIFT;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            copy(mByteStore.getInputStream(), sink.outputStream());
        }
    };
    try {
        Request.Builder builder = new Request.Builder().url(mUrl).post(requestBody);
        if (mHeaders != null) {
            for (String name : mHeaders.keySet()) {
                builder.header(name, mHeaders.get(name));
            }
        }
        Response response = mHttpClient.newCall(builder.build()).execute();
        if (response.code() != 200) {
            throw new TTransportException("HTTP Response code: " + response.code() + ", message " + response.message());
        }
        mResponseBody = response.body().byteStream();
    } catch (Exception e) {
        throw new TTransportException(e);
    } finally {
        try {
            mByteStore.reset();
        } catch (IOException ignored) {
        }
    }
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) TTransportException(com.evernote.thrift.transport.TTransportException) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) IOException(java.io.IOException) TTransportException(com.evernote.thrift.transport.TTransportException) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

RequestBody (com.squareup.okhttp.RequestBody)20 Request (com.squareup.okhttp.Request)19 Response (com.squareup.okhttp.Response)13 IOException (java.io.IOException)13 OkHttpClient (com.squareup.okhttp.OkHttpClient)8 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 MediaType (com.squareup.okhttp.MediaType)3 MultipartBuilder (com.squareup.okhttp.MultipartBuilder)3 Intent (android.content.Intent)2 Call (com.squareup.okhttp.Call)2 CookieManager (java.net.CookieManager)2 BufferedSink (okio.BufferedSink)2 JSONException (org.json.JSONException)2 JSONObject (org.json.JSONObject)2 AccountAuthenticatorResponse (android.accounts.AccountAuthenticatorResponse)1 AccountManager (android.accounts.AccountManager)1 SharedPreferences (android.content.SharedPreferences)1 Bundle (android.os.Bundle)1 QAException (cn.jeesoft.qa.error.QAException)1