개조 2-동적 URL 내 응용 프로그램에서 웹 서비스의 URL을 컴파일

Retrofit 2를 사용하면 다음과 같은 서비스 방법 주석에 전체 URL을 설정할 수 있습니다.

public interface APIService {
  @GET("http://api.mysite.com/user/list")
  Call<Users> getUsers();
}

그러나 내 응용 프로그램에서 웹 서비스의 URL을 컴파일 타임에 알 수 없으며 응용 프로그램이 다운로드 된 파일에서 URL을 검색하므로 전체 동적 URL과 함께 Retrofit 2를 어떻게 사용할 수 있는지 궁금합니다.

나는 다음과 같은 전체 경로를 설정하려고했습니다.

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path("fullUrl") fullUrl);
}

new Retrofit.Builder()
  .baseUrl("http://api.mysite.com/")
  .build()
  .create(APIService.class)
  .getUsers("http://api.mysite.com/user/list"); // this url should be dynamic
  .execute();

그러나 여기서 Retrofit은 경로가 실제로 전체 URL이며 다운로드하려고한다는 것을 알지 못합니다. http://api.mysite.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist

그런 동적 URL과 함께 Retrofit을 사용하는 방법에 대한 힌트가 있습니까?

감사합니다



답변

나는 당신이 그것을 잘못된 방식으로 사용하고 있다고 생각합니다. 다음은 changelog 에서 발췌 한 것입니다 .

@Url 매개 변수 주석을 사용하면 엔드 포인트에 대한 완전한 URL을 전달할 수 있습니다.

따라서 인터페이스는 다음과 같아야합니다.

public interface APIService {
    @GET
    Call<Users> getUsers(@Url String url);
}


답변

URL의 일부만 바꾸고 싶었고이 솔루션을 사용하면 전체 URL을 전달할 필요가 없으며 동적 부분 만 전달하면됩니다.

public interface APIService {

  @GET("users/{user_id}/playlists")
  Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}


답변

주석 에서 인코딩 된 플래그를 사용할 수 있습니다 @Path.

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
  • 로 교체하지 못하게 /됩니다 %2F.
  • 그것은 당신이 저장에서이되지 않습니다 ?으로 대체 %3F당신은 여전히 동적 쿼리 문자열에 통과 할 수 있도록, 그러나.

답변

Retrofit 2.0.0-beta2 기준으로이 URL에서 JSON에 응답하는 서비스가있는 경우 :
http : // myhost / mypath

다음은 작동하지 않습니다.

public interface ClientService {
    @GET("")
    Call<List<Client>> getClientList();
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList().execute();

그러나 이것은 괜찮습니다.

public interface ClientService {
    @GET
    Call<List<Client>> getClientList(@Url String anEmptyString);
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList("").execute();


답변

이것을 사용할 수 있습니다 :

@GET("group/{id}/users")

Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

자세한 내용은 설명서 https://square.github.io/retrofit/를 참조 하십시오.


답변

1 단계

  Please define a method in Api interface like:-
 @FormUrlEncoded
 @POST()
 Call<RootLoginModel> getForgotPassword(
        @Url String apiname,
        @Field(ParameterConstants.email_id) String username
 );

2 단계
모범 사례를 위해 개량 인스턴스의 클래스를 정의하십시오.

  public class ApiRequest {
       static Retrofit retrofit = null;



public static Retrofit getClient() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
            .addInterceptor(logging)
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .build();

    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(URLConstants.base_url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}
3 단계
는 활동을 정의합니다.

  final APIService request =ApiRequest.getClient().create(APIService.class);
  Call<RootLoginModel> call = request.getForgotPassword("dynamic api
  name",strEmailid);


답변

kotlin으로 작성된 RetrofitHelper 라이브러리를 사용하면 몇 줄의 코드를 사용하여 API 호출을 할 수 있으며 모든 호출에서 다른 URL, 헤더 및 매개 변수를 사용할 수 있습니다 .

다음과 같이 애플리케이션 클래스에 여러 개의 URL을 추가하십시오.

class Application : Application() {

    override fun onCreate() {
    super.onCreate()

        retrofitClient = RetrofitClient.instance
                    //api url
                .setBaseUrl("https://reqres.in/")
                    //you can set multiple urls
        //                .setUrl("example","http://ngrok.io/api/")
                    //set timeouts
                .setConnectionTimeout(4)
                .setReadingTimeout(15)
                    //enable cache
                .enableCaching(this)
                    //add Headers
                .addHeader("Content-Type", "application/json")
                .addHeader("client", "android")
                .addHeader("language", Locale.getDefault().language)
                .addHeader("os", android.os.Build.VERSION.RELEASE)
            }

        companion object {
        lateinit var retrofitClient: RetrofitClient

        }
    }  

그런 다음 전화에 필요한 URL을 사용하십시오.

retrofitClient.Get<GetResponseModel>()
            //set base url
            .setBaseUrlKey("example")
            //set path
            .setPath("api/users/2")
            //set url params Key-Value or HashMap
            .setUrlParams("KEY","Value")
            .setResponseHandler(GetResponseModel::class.java,
                object : ResponseHandler<GetResponseModel>() {
                    override fun onSuccess(response: Response<GetResponseModel>) {
                        super.onSuccess(response)
                        //handle response
                    }
                }).run(this)

자세한 내용은 설명서를 참조하십시오