Retrofit调用根URL为BASE_URL,而不是完整的BASE_URL。

huangapple go评论72阅读模式
英文:

Retrofit Calling Root url of BASE_URL instead of full BASE_URL

问题

每当我使用Retrofit调用带有/user/block端点的API时,Retrofit会使用BASE_URL的根URL而不是完整的BASE_URL

例如,如果我的BASE_URL是:

BASE_URL = "http://111.111.111.11/SocialApi/public/";

那么API调用应该是BASE_URL + endPoint,但实际上API调用是在基本URL的根目录上:

http://111.111.111.11/user/block

所以会收到 404 Not Found 响应。

我在这里到底做错了什么?

英文:

Whenever I am calling the API with endPoint /user/block using retrofit, The retrofit calling the API with root Url of the BASE_URL instead of full BASE_URL.

Like if my BASE_URL is.

BASE_URL = "http://111.111.111.11/SocialApi/public/";

Then the API call should be go on BASE_URL+endPoint, But the Api call is going on root of base Url,

http://111.111.111.11/user/block

So getting 404 Not Found response.

What actually I am doing wrong here?

Retrofit调用根URL为BASE_URL,而不是完整的BASE_URL。

My singleton class, ApiClient.java.

package com.socialcodia.famblah.api;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.socialcodia.famblah.SocialCodia;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    private static final String BASE_URL = "http://111.111.111.11/SocialApiFriendsSystemVideoThumb/public/";
    public static final String HEADER_CACHE_CONTROL = "Cache-Control";
    public static final String HEADER_PRAGMA = "Pragma";
    private static final String TAG = "ServiceGenerator";
    private static ApiClient mInstance;

    private Retrofit retrofit;
    public static final long CACHE_SIZE = 5 * 1024 * 1024;

    private ApiClient()
    {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

    private static OkHttpClient okHttpClient(){
        return new OkHttpClient.Builder()
                .cache(cache())
                .addInterceptor(httpLoggingInterceptor())
                .addNetworkInterceptor(networkInterceptor())
                .addInterceptor(offlineInterceptor())
                .build();
    }

    private static Cache cache()
    {
        return new Cache(new File(SocialCodia.getInstance().getCacheDir(),"socialcodia"),CACHE_SIZE);
    }

    private static  HttpLoggingInterceptor httpLoggingInterceptor()
    {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("mufazmi",message);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return httpLoggingInterceptor;
    }

    private static Interceptor networkInterceptor()
    {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response =chain.proceed(chain.request());
                CacheControl cacheControl = new CacheControl.Builder()
                        .maxAge(20, TimeUnit.SECONDS)
                        .build();

                return response.newBuilder()
                        .removeHeader(HEADER_PRAGMA)
                        .removeHeader(HEADER_CACHE_CONTROL)
                        .header(HEADER_CACHE_CONTROL,cacheControl.toString())
                        .build();
            }
        };
    }

    public static Interceptor offlineInterceptor()
    {
        return  new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!SocialCodia.isNetworkOk())
                {
                    CacheControl cacheControl = new CacheControl.Builder()
                            .maxStale(7,TimeUnit.DAYS)
                            .build();

                    request = request.newBuilder()
                            .removeHeader(HEADER_PRAGMA)
                            .removeHeader(HEADER_CACHE_CONTROL)
                            .cacheControl(cacheControl)
                            .build();
                }
                return  chain.proceed(request);
            }
        };
    }

    public static synchronized ApiClient getInstance()
    {
        if (mInstance == null)
        {
            mInstance = new ApiClient();
        }
        return mInstance;
    }

    public Api getApi()
    {
        return retrofit.create(Api.class);
    }

}

My API interface.

package com.socialcodia.famblah.api;


import com.socialcodia.famblah.pojo.ResponseDefault;


import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Header;
import retrofit2.http.POST;

import static com.socialcodia.famblah.storage.Constants.USER_TOKEN;
import static com.socialcodia.famblah.storage.Constants.USER_ID;

public interface Api
{

    @FormUrlEncoded
    @POST("/user/block")
    Call<ResponseDefault> doBlock(
            @Header(USER_TOKEN) String token,
            @Field(USER_ID) int userId
    );


    @FormUrlEncoded
    @POST("acceptFriendRequest")
    Call<ResponseDefault> acceptFriendRequest(
            @Header(USER_TOKEN) String token,
            @Field(USER_ID) int userId
    );

}

Method to call api from ProfileActivity

private void doBlock()
{
    Call<ResponseDefault> call = ApiClient.getInstance().getApi().doBlock(token,hisUserId);
    call.enqueue(new Callback<ResponseDefault>() {
        @Override
        public void onResponse(Call<ResponseDefault> call, Response<ResponseDefault> response) {
            if (response.isSuccessful())
            {
                ResponseDefault responseDefault = response.body();
                Toast.makeText(ProfileActivity.this, responseDefault.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onFailure(Call<ResponseDefault> call, Throwable t) {
            Toast.makeText(ProfileActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            t.printStackTrace();
        }
    });
}

But when I am calling the acceptFriendRequest() method it's working. means it calling the API.

Retrofit调用根URL为BASE_URL,而不是完整的BASE_URL。

Method to accept friend request.

   private void acceptFriendRequest()
    {
        if (Utils.isNetworkAvailable(getApplicationContext()))
        {
            btnAcceptFriendRequest.setEnabled(false);
            Call<ResponseDefault> call = ApiClient.getInstance().getApi().acceptFriendRequest(token,hisUserId);
            call.enqueue(new Callback<ResponseDefault>() {
                @Override
                public void onResponse(Call<ResponseDefault> call, Response<ResponseDefault> response) {
                    if (response.isSuccessful())
                    {
                        ResponseDefault responseDefault = response.body();
                        if (!responseDefault.getError())
                        {
                            btnAcceptFriendRequest.setEnabled(true);
                            btnRejectFriendRequest.setVisibility(View.GONE);
                            btnAcceptFriendRequest.setVisibility(View.GONE);
                            btnUnFriend.setVisibility(View.VISIBLE);
                        }
                        else
                        {
                            btnAcceptFriendRequest.setEnabled(true);
                            Toast.makeText(ProfileActivity.this, responseDefault.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                    else
                    {
                        btnAcceptFriendRequest.setEnabled(true);
                        Toast.makeText(ProfileActivity.this, R.string.SNR, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseDefault> call, Throwable t) {
                    btnAcceptFriendRequest.setEnabled(true);
                    t.printStackTrace();
                }
            });
        }
    }

答案1

得分: 0

我已经通过从 endPoint /user/block 中移除斜杠来解决了这个问题。

@FormUrlEncoded
@POST("user/block")
Call<ResponseDefault> doBlock(
        @Header(USER_TOKEN) String token,
        @Field(USER_ID) int userId
);
英文:

I have solve this by removing the slash from endPoint /user/block

@FormUrlEncoded
@POST(&quot;user/block&quot;)
Call&lt;ResponseDefault&gt; doBlock(
        @Header(USER_TOKEN) String token,
        @Field(USER_ID) int userId
);

huangapple
  • 本文由 发表于 2020年10月16日 00:26:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64375883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定