如何在android中使用同步方法上传图像

时间:2018-04-04 09:42:25

标签: android android-layout retrofit

我想使用改造同步方法在android上传图像。我用如下所示的齐射异步做了这个,但现在我想用同步做这个。

<?php
header("Content-Type: application/json");

有人知道如何通过改造或其他库来实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

interface ImageService {
    @POST Call<String> upload(@Url HttpUrl url, @QueryMap Map<String, String> options);
}

private ImageService getImageService() {

    Dispatcher dispatcher = new Dispatcher(Executors.newFixedThreadPool(20));
    dispatcher.setMaxRequests(20);
    dispatcher.setMaxRequestsPerHost(1);

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .dispatcher(dispatcher)
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .connectionPool(new ConnectionPool(100, 30, TimeUnit.SECONDS))
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(HttpUrl.parse("https://example.com/"))
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    return retrofit.create(ImageService.class);
}

private void uploadImage(final String image_path) {

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("postedFile", img_path);
    parameters.put("folderName", estimateNumber.getText().toString());
    parameters.put("catName", EstimateID.getText().toString());
    parameters.put("estNumber", estimateNumber.getText().toString());
    parameters.put("userName", uploadDestination.getText().toString().concat("/Images"));
    parameters.put("imageUploadID", "2017-10-09 01.43.36 PM");
    parameters.put("dateTime", "2017-10-09 01.43 PM");
    parameters.put("type", "image");
    parameters.put("accessToken", "fgd3Rh@lcr");
    parameters.put("fileName", estNumber.getText().toString().concat(fileNameList.get(j)));

    getImageService().upload(HttpUrl.parse(UPLOAD_URL), parameters).enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            //Disimissing the progress dialog
            loading.dismiss();
            //Showing toast message of the response
            Toast.makeText(ImageUploadActivity.this, "Success", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(ImageUploadActivity.this, CameraActivity.class);
            startActivity(i);
            finish();
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            //Showing toast
            Toast.makeText(ImageUploadActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            //Dismissing the progress dialog
            loading.dismiss();
        }
    });
}