【问题标题】:Post request error using retrofit android使用改造android发布请求错误
【发布时间】:2019-05-14 16:08:44
【问题描述】:

我在我的应用程序上使用 Retrofit 从服务器下载视频文件,在请求中我需要执行 Post 请求, 在界面上我添加了所需的参数....在java函数上我也传递了参数,但是 当我尝试运行代码时出现错误:

java.lang.RuntimeException:执行时出错 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();
        }
    });
}

【问题讨论】:

  • 我认为你不应该使用 Retrofit 和 AsyncTask。

标签: java android retrofit retrofit2


【解决方案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'

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    相关资源
    最近更新 更多