【问题标题】:How to write similar Retrofilt code for OKHTTP format?如何为 OKHTTP 格式编写类似的 Retrofilt 代码?
【发布时间】:2021-06-29 00:45:37
【问题描述】:

我的 OKHttp 代码运行良好,但有时无法进入 ENQUEUE。它没有显示任何关于它的信息。我正在尝试在 Retrofit 语法中转换相同的代码。任何人都可以帮助我使用正确的语法吗?

file1/2/3下面是图片文件路径。

OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("photos1", String.valueOf(file1),
                            RequestBody.create(MediaType.parse("application/octet-stream"),
                                    new File(String.valueOf(file2)) ))
                    .addFormDataPart("photos2", String.valueOf(file2),
                            RequestBody.create(MediaType.parse("application/octet-stream"),
                                    new File(String.valueOf(file3)) ))
                    .addFormDataPart("photos3", String.valueOf(file3),
                            RequestBody.create(MediaType.parse("application/octet-stream"),
                                    new File(String.valueOf(file1)) ))
                    .addFormDataPart("product_name",txtprodname.getText().toString())
                    .addFormDataPart("description",txtdesc.getText().toString())
                    .addFormDataPart("product_cost",txtprice.getText().toString())
                    .addFormDataPart("tax_value",spntax.getSelectedItem().toString())
                    .addFormDataPart("within_city_cost",txtcostwithincity.getText().toString())
                    .addFormDataPart("outside_city_cost",txtcostoutsideincity.getText().toString())
                    .addFormDataPart("user_id",String.valueOf(user_id))
                    .addFormDataPart("category_name", spncategory.getSelectedItem().toString())
                    .addFormDataPart("tax_name",taxname)
                    .addFormDataPart("business_name", business_name)
                    .addFormDataPart("youtube_link", txtyoutube.getText().toString())
                    .addFormDataPart("length", txtL.getText().toString())
                    .addFormDataPart("width", txtW.getText().toString())
                    .addFormDataPart("height", txtH.getText().toString())
                    .addFormDataPart("volumetric_weight", txtwt.getText().toString())
                    .build();

            Request request = new Request.Builder()
                    .url("https://<myip>/api/productapi/")
                    .method("POST", body)
                    .build();

client.newCall(request).enqueue(new okhttp3.Callback() .... rest of the code.

我无法弄清楚 Retrofit 的类似语法。任何帮助将不胜感激。

问候, PD

【问题讨论】:

    标签: android retrofit retrofit2 okhttp


    【解决方案1】:

    如果您需要使用 Retrofit 在 API 中发送任何文件,那么您需要按照以下步骤操作。

    1. 改造初始化创建类APIClient
    public class APIClient {
        public static Retrofit retrofit;
    
        public static Retrofit getClient() {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS).writeTimeout(120, TimeUnit.SECONDS).build();
            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl("https://myapi.com")
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .client(client)
                        .build();
            }
            return retrofit;
        }
    
    1. 创建一个接口以列出 API 密钥,考虑接口名称 APiInterfacr。 最重要的是将 RequestBody 的 DataType 分配给您的所有 String/Int 数据...并分配 MultiPartBody.Part em> 只归档.. 用户是我的对象等级,您需要创建您的对象等级并替换...
    
    public interface APIInterface {
        @Multipart
        @POST("xyznode")
        Call<Users> updateUser(@Part("id") RequestBody id,
                               @Part("name") RequestBody name,
                               @Part("email") RequestBody email,
                               @Part("password") RequestBody password,
                               @Part("paypal_address") RequestBody paypal_address,
                               @Part("user_location") RequestBody user_location,
                               @Part("role_id") RequestBody role_id,
                               @Part MultipartBody.Part image_url);
    
    }
    
    1. 现在需要调用 API。
      public void updateUser(RequestBody id, RequestBody name, RequestBody email, RequestBody password, RequestBody paypal_address, RequestBody user_location, MultipartBody.Part profile_photo_url, RequestBody role) {
            if (NetworkConnectivity.isOnline()) {
                Call<Users> call = apiInterface.updateUser(id, name, email, password, paypal_address, user_location, role, profile_photo_url);
                call.enqueue(new Callback<Users>() {
                    @Override
                    public void onResponse(Call<Users> call, Response<Users> response) {
                        if (response.isSuccessful()) {
                         
               //Do your stuff here...
                        }
                    }
    
                    @Override
                    public void onFailure(Call<Users> call, Throwable t) {
    //
                    }
                });
            } 
        }
    
    1. 最重要的是调用这个特定的函数,为此您需要列出在 API 中打包所需的所有内容...
                           RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
                            profileImage = MultipartBody.Part.createFormData("profile_photo_url", file.getName(), fileReqBody);
                            RequestBody id = RequestBody.create(MediaType.parse("multipart/form-data"), preferencesHandler.getUid());
                            RequestBody name = RequestBody.create(MediaType.parse("multipart/form-data"), txt_name);
                            RequestBody email = RequestBody.create(MediaType.parse("multipart/form-data"), txt_email);
                            RequestBody password = RequestBody.create(MediaType.parse("multipart/form-data"), txt_password);
                            RequestBody roleid = RequestBody.create(MediaType.parse("multipart/form-data"), preferencesHandler.getRole());
                            RequestBody country = RequestBody.create(MediaType.parse("multipart/form-data"), txt_country);
                            RequestBody paypal = RequestBody.create(MediaType.parse("multipart/form-data"), txt_paypal);
    
    1. 现在调用函数..
    onUpdateUser(id, name, email, password, paypal, country, roleid, profileImage);
    
    1. 要在构建文件中添加的依赖项。
    //Retrofit Dependency
        implementation 'com.squareup.retrofit2:retrofit:2.1.0'
        implementation 'com.google.code.gson:gson:2.6.2'
        implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
        implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    

    现在你准备好了... :-)

    【讨论】:

    • 好的,我将尝试执行与我的代码有关的内容。
    • @user15226396 好的,如果您得到答案,请将其标记为已接受...
    猜你喜欢
    • 2016-12-07
    • 2011-02-03
    • 1970-01-01
    • 2020-10-05
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多