有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用改型安卓的java Post请求错误

我在我的应用程序上使用改型从服务器下载一个视频文件,在请求中我需要做一个Post请求, 在界面上,我添加了所需的参数。。。。关于java函数,我也在传递参数,但是 当我试图运行代码时,我得到一个错误:

java.lang.RuntimeException: An error occurred while executing doInBackground()

@Headers("Content-Type: application/json; charset=UTF-8")
@Streaming
@POST
Call<ResponseBody> downloadFileStream(@Url String url, @QueryMap Map<String, Object> postdata);

private void downloadFile(String url) { 

    FileDownloadClient fileDownloadClient = retrofit.create(FileDownloadClient.class);

    Call<ResponseBody> call = fileDownloadClient.downloadFileStream(url,postdata);
    postdata.put("user", "test@test.com");
    postdata.put("test", "test");

    Call<ResponseBody> call = fileDownloadClient.downloadFileStream(url, postdata);

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    boolean success = writeResponseBodyToDisk(response.body());

                    return null;
                }
            }.execute();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Mal", Toast.LENGTH_LONG).show();
        }
    });
}

共 (1) 个答案

  1. # 1 楼答案

    我也有同样的问题,试试这个。。。这对我有用

    你的界面:

    public interface FileDownloadClient {
        @Streaming
        @POST("yourAPI")
        Call<ResponseBody> downloadFileStream(@Body Map<String, Object> postdata);
    }
    

    在下载文件中更改此选项:

    private void downloadFile() {
            Retrofit.Builder builder = new Retrofit.Builder().baseUrl("yourwebsite/api/")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create());
    
            Retrofit retrofit = builder.build();
    
            FileDownloadClient fileDownloadClient = retrofit.create(FileDownloadClient.class);
    
            Map<String, Object> postdata = new HashMap<>();
            postdata.put("user", "test@test.com");
            postdata.put("test", "test");
    
            Call<ResponseBody> call = fileDownloadClient.downloadFileStream(postdata);
    }
    

    格兰德尔:

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.google.code.gson:gson:2.6.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'