【问题标题】:How do I use Retrofit instead of Volley to send an image to my server?如何使用 Retrofit 而不是 Volley 将图像发送到我的服务器?
【发布时间】:2017-01-14 21:57:39
【问题描述】:

我应该如何在此代码中实施改造以将图像发送到服务器而不是使用 Volley?我有点困惑,因为我对 Java/Android 有点陌生。我想要一些关于如何使用 Retrofit 来实现这一点的指导,因为 Volley 似乎不起作用。

我基本上是在向我的服务器发送图像的 base64 字符串以及图像名称和稍后的其他一些内容。我还需要从我的服务器检索响应并将其显示在我的应用程序上。 Volley 似乎很容易做到这一点,不确定 Retrofit。

提前致谢

public class MainActivity extends AppCompatActivity {

private ImageButton ImageButton;
private String encoded_string, image_name;
private Bitmap bitmap;
private File file;
private Uri file_uri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageButton = (ImageButton) findViewById(R.id.camera);
    ImageButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            getFileUri();
            i.putExtra(MediaStore.EXTRA_OUTPUT,file_uri);
            startActivityForResult(i,10);
        }
    });
}

private void getFileUri() {
    image_name = "testing123.jpeg";
    file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), image_name);

    file_uri = Uri.fromFile(file);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == 10 && resultCode == RESULT_OK){
        new Encode_image().execute();
    }
}

private class Encode_image extends AsyncTask<Void,Void,Void> {
   @Override
   protected Void doInBackground(Void... voids){

       bitmap = BitmapFactory.decodeFile(file_uri.getPath());
       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);

       byte[] array = stream.toByteArray();
       encoded_string = Base64.encodeToString(array,0);
       return null;
   }

   @Override
   protected void onPostExecute(Void aVoid){
       makeRequest();
   }
}

private void makeRequest() {
    final TextView mTextView = (TextView) findViewById(R.id.text);
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://128.199.77.211/server/connection.php";
    StringRequest request = new StringRequest(Request.Method.POST, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    mTextView.setText(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> map = new HashMap<>();
            map.put("encoded_string", encoded_string);
            map.put("image_name", image_name);

            return map;
        }
    };
    requestQueue.add(request);
  }
}

【问题讨论】:

标签: java android retrofit retrofit2


【解决方案1】:

使用 Retrofit 2,您需要使用 OkHttp 的 RequestBody 或 MultipartBody.Part 类,并将您的文件封装到请求正文中。我们来看看文件上传的接口定义。

public interface FileUploadService {  
    @Multipart
    @POST("upload")
    Call<ResponseBody> upload(@Part("description") RequestBody description,
                              @Part MultipartBody.Part file);
}

在 Java 文件中

private void uploadFile(Uri fileUri) {  
    // create upload service client
    FileUploadService service =
            ServiceGenerator.createService(FileUploadService.class);

    // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
    // use the FileUtils to get the actual file by uri
    File file = FileUtils.getFile(this, fileUri);

    // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

    // add another part within the multipart request
    String descriptionString = "hello, this is description speaking";
    RequestBody description =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), descriptionString);

    // finally, execute the request
    Call<ResponseBody> call = service.upload(description, body);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call,
                               Response<ResponseBody> response) {
            Log.v("Upload", "success");
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("Upload error:", t.getMessage());
        }
    });
}

【讨论】:

  • 我真的很困惑,我不知道如何实现。
  • @RQ14 你必须参考改造教程
  • 我正在努力用我的代码来实现它。尤其是相机意图。
【解决方案2】:

从您的图像创建MultipartBody.Part 对象。

File imageIdCard = new File(image_path);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), imageIdCard);
MultipartBody.Part bodyImage = MultipartBody.Part.createFormData("image_id", imageIdCard.getName(), requestFile);

然后上传

@Multipart
@POST("url")
Call<JsonObect> getResponse(@Part MultipartBody.Part image);

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 2015-10-20
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2018-02-16
    • 2014-11-06
    • 1970-01-01
    相关资源
    最近更新 更多