当前位置: 首页 > 知识库问答 >
问题:

如何使用Retrofit而不是Volley将图像发送到我的服务器?

罗淮晨
2023-03-14

我应该如何实现改造到这个代码发送图像到服务器,而不是使用Volley?我有点困惑,因为我对Java有点陌生 /Android.我想知道一些关于如何使用改造实现这一点的指导,因为Volley似乎不工作。

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

提前谢谢

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);
  }
}

共有2个答案

丁振海
2023-03-14

创建多部件主体。从图像中分割对象。

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);
阎庆
2023-03-14

使用改型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());
        }
    });
}
 类似资料:
  • 问题内容: 我想通过齐射库 {“ user_id”:12,“ answers”:{“ 11”:3,“ 12”:4,“ 13”:5}}* 将以下格式的jsonobject发送到服务器 * 如果我想使用 StringRequest, 如何使用POST方法将此JsonObject发送到服务器 问题答案: 您可以使用以下工作示例代码。我测试过了 希望这可以帮助! 更新: 要创建JSONObject作为您的

  • 问题内容: 我想使用POST方法将JSONObject发送到服务器。我已经使用凌空库通过字符串参数来正常工作,但是如果我尝试使用json对象,则在调用json对象时显示错误,这是我的代码 我的错误表单服务器是: 如何解决这个问题呢。我要添加 标题,请检查我的代码是否正确。请给我一个解决这个问题的建议 问题答案: JsonObjectRequest中的第三个参数用于以jsonobject形式传递发布

  • 我必须向服务器发送一个映像(我认为最好的选择是使用HttpURLConnection)并从它接收一个字符串答案。在我读过的不同的文档和web站点中,我研究了这样做的最佳方法是使用多伙伴关系。 1_做它是最好的解决方案吗? 2_我有一个错误,说Android Studio无法解析符号'multipartentity'。我读到,要解决它,我必须下载外部库。哪些是它们,我如何下载它们? 3_为此,我想在

  • 我要做的是在Dropzone之前。js将删除的图像发送到服务器,会出现一个带有裁剪器的模式。js(fengyuanchen脚本),用户可以裁剪图像,当图像被裁剪时,用Dropzone发送。js连接到服务器。 因此,当我用函数fileToBase64更改#cropbox的图像src,并用函数croper('replace')替换裁剪器的图像时,它会一直显示默认值。jpg图片,而不是用户上传的新图片

  • 问题内容: 我的问题是可以使用ajax(jquery)将图像上传到服务器吗 以下是我的ajax脚本,无需重新加载页面即可发送文本 是否可以修改它以发送图像? 问题答案: 这可行。 是您要找的东西吗?

  • 问题内容: 我要上传图像并将其保存在服务器中。我上传了图像并获得了预览,但是我被困在将图像发送到服务器上。我想使用角度服务将此图像发送到服务器。 这是HTML代码 这是指令 问题答案: 假设您在后端中期望Multipart,这是一段对我有用的代码。 这是一个jsfiddle。 请注意 以下部分: 是一些Angular魔术,为了使$ http解析FormData并找到正确的内容类型,等等。