Search in sources :

Example 1 with MultipartBuilder

use of com.squareup.okhttp.MultipartBuilder 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 2 with MultipartBuilder

use of com.squareup.okhttp.MultipartBuilder in project PocketHub by pockethub.

the class ImageBinPoster method post.

/**
     * Post the image to ImageBin
     *
     * @param bytes Bytes of the image to post
     * @param callback Request callback
     */
public static void post(byte[] bytes, Callback callback) {
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", "test", RequestBody.create(MediaType.parse("image/*"), bytes)).build();
    Request request = new Request.Builder().url("https://imagebin.ca/upload.php").post(requestBody).build();
    OkHttpClient client = new OkHttpClient();
    Call call = client.newCall(request);
    call.enqueue(callback);
}
Also used : Call(com.squareup.okhttp.Call) OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) RequestBody(com.squareup.okhttp.RequestBody)

Example 3 with MultipartBuilder

use of com.squareup.okhttp.MultipartBuilder in project QuickAndroid by ImKarl.

the class OkHttp method createRequest.

private <T> Request createRequest(QAHttpMethod method, String url, QARequestParams params, final QAHttpCallback<T> listener) {
    if (method == null) {
        method = QAHttpMethod.GET;
    }
    final String finalUrl = url;
    if (method == QAHttpMethod.GET) {
        url = parseGetUrl(url, params != null ? params.getParams() : null);
        params = null;
    } else {
        if (params == null) {
            params = new QARequestParams();
        }
    }
    Request.Builder builder = new Request.Builder();
    try {
        builder.url(url);
    } catch (final Exception e) {
        sendFailedCallback(finalUrl, e, listener);
        return null;
    }
    // 强制使用缓存
    builder.cacheControl(CacheControl.FORCE_CACHE);
    // header
    Headers.Builder headerBuilder = new Headers.Builder();
    if (params != null && !params.getHeaders().isEmpty()) {
        for (Entry<String, String> entry : params.getHeaders().entrySet()) {
            headerBuilder.add(entry.getKey(), entry.getValue());
        }
    }
    builder.headers(headerBuilder.build());
    // param
    RequestBody requestBody = null;
    if (params != null) {
        if (!TextUtils.isEmpty(params.getBody())) {
            requestBody = RequestBody.create(MEDIA_TYPE_TEXT, params.getBody());
        } else {
            try {
                MultipartBuilder paramBuilder = new MultipartBuilder();
                if (params != null && !params.getParams().isEmpty()) {
                    for (Entry<String, List<Part>> entry : params.getParams().entrySet()) {
                        String name = entry.getKey();
                        List<Part> parts = entry.getValue();
                        if (parts != null && !parts.isEmpty()) {
                            for (Part part : parts) {
                                paramBuilder.addPart(part.header(), part.body());
                            }
                        }
                    }
                }
                requestBody = paramBuilder.build();
            } catch (IllegalStateException e) {
                requestBody = new FormEncodingBuilder().build();
            }
        }
    }
    builder.method(method.name(), requestBody == null ? null : new ProgressRequestBody(requestBody, new OnProgressListener() {

        @Override
        public void onProgress(long currentBytes, long contentLength) {
            // 上传进度
            sendProgressCallback(finalUrl, currentBytes, contentLength, QAHttpAction.REQUEST, listener);
        }
    }));
    final Request request = builder.build();
    mOnProgressListeners.put(request, new OnProgressListener() {

        @Override
        public void onProgress(long currentBytes, long contentLength) {
            // 下载进度
            sendProgressCallback(finalUrl, currentBytes, contentLength, QAHttpAction.RESPONSE, listener);
        }
    });
    return request;
}
Also used : Headers(com.squareup.okhttp.Headers) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) QANullException(cn.jeesoft.qa.error.QANullException) QANoSupportException(cn.jeesoft.qa.error.QANoSupportException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) QAException(cn.jeesoft.qa.error.QAException) IOException(java.io.IOException) StringPart(cn.jeesoft.qa.libcore.http.part.StringPart) Part(cn.jeesoft.qa.libcore.http.part.Part) List(java.util.List) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) QARequestParams(cn.jeesoft.qa.libcore.http.QARequestParams) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

MultipartBuilder (com.squareup.okhttp.MultipartBuilder)3 Request (com.squareup.okhttp.Request)3 RequestBody (com.squareup.okhttp.RequestBody)3 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 QAException (cn.jeesoft.qa.error.QAException)1 QANoSupportException (cn.jeesoft.qa.error.QANoSupportException)1 QANullException (cn.jeesoft.qa.error.QANullException)1 QARequestParams (cn.jeesoft.qa.libcore.http.QARequestParams)1 Part (cn.jeesoft.qa.libcore.http.part.Part)1 StringPart (cn.jeesoft.qa.libcore.http.part.StringPart)1 Call (com.squareup.okhttp.Call)1 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)1 Headers (com.squareup.okhttp.Headers)1 OkHttpClient (com.squareup.okhttp.OkHttpClient)1 Response (com.squareup.okhttp.Response)1 Realm (io.realm.Realm)1 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1