Make more #path in Retrofit URL - android

I need help on how to use more than one parameter '#path' in retrofit request. I tried using single parameter '#Path' this way it worked.
#GET("topics/{id}?userId=58bf87d343c3ccb5793b2e99")
Call<ResponseBody> artikel(#Path("id") String id);
but I want to use two parameters like this
ApiService.class :
#GET("topics/{id}?userId={userId}")
Call<ResponseBody> artikelFeeds(#Path("id") String id, #Path("userId") String userId);
which throws error 'path must not have replace block'
and this is the part of retrofit client
Call<ResponseBody> get_artikel;
Retrofit retrofit;
retrofit = new Retrofit.Builder()
.baseUrl(Status.HOST_ARTICLE)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
ApiService apiService = retrofit.create(ApiService.class);
get_artikel = apiService.artikelFeeds(id,userId);

try this,
#GET("topics/{id}")
Call<ResponseBody> artikelFeeds(#Path("id") String id, #Query("userId") String userId);

You make a query after ? sign, so you need to annotate with #Query
#GET("topics/{id}Call<ResponseBody> artikelFeeds(#Path("id") String id, #Query("userId") String userId);

Related

How to know right headers for API request?

I'm trying to hit this POST API from last 2 hours, but I'm stuck with this error.
public interface ApiInterface {
/*POST API*/
#Headers(HEADER)
#POST("Api/signup")
Call<String> addSignUpData(#Body SignUp signUp);
}
Set your Base url to:
public static final String BASE_URL =
"http://clarigoinfotech.co.in/";
GSon can't parse your json from your objects, Please change your response to json object
or create an entity class for your response
Call<JsonObject> addSignUpData(#Body SignUp signUp)
or
Call<SignupResult> addSignUpData(#Body SignUp signUp)
public SignupResult{
boolean response ;
String message;
...
}
your header must be in this format
#Headers("Accept: application/json")
and add GsonConverterFactory to your retrofit service :
Retrofit.Builder()
.client(client)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build

Error 401 from retrofit even after setting the Authorization Token

Trying to access an api with #POST and I already set my #Header("Authorization") String TOKEN.
I've tried it with #GET and it worked, but I'm passing a some form fields so I need to use #POST
#POST("details")
#FormUrlEncoded
Call<Play> playTrack(
#Header("Authorization") String TOKEN,
#Field("event_id") int event_id,
#Field("longitude") double longitude,
#Field("latitude") double latitude
);
Try to create a header interceptor and add it to OkHttpClient :
Interceptor headerIntercepter = new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
return chain.proceed( chain.request().newBuilder().addHeader("authorization-
client", accessToken).build());
}
};
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS)
.addInterceptor(headerIntercepter)
.build();
try {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Server_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(Api.class);
try using Multipart on annotation
#Multipart
#POST("details")
Call<ResponseBody> playTrack(
#Header("Authorization") String token,
#Part("event_id") RequestBody eventId,
#Part("longitude") RequestBody longitude,
#Part("latitude") RequestBody latitude,
);
make sure to pass a RequestBody as params
val latitude = RequestBody.create(MediaType.parse("text/plain"), doubleLatitude.toString())
Seeing a 401 response means that the request was successfully executed
and the server returned that status code. This is not a problem with
Retrofit, but in whatever authentication information you are including
in the request that the server expects.
Try with postman with the same data and check
N.B: Don't forgot to add Token Type as prefix to your token

How to Make Retrofit Method Get Without Parameter?

i want Get Data with retrofit and i have problem, i will expain with code
ApiService.class :
public interface ApiService {
#GET
Call<ResponseBody> artikel();
}
and my procces class
Call<ResponseBody> get_artikel;
Retrofit retrofit;
retrofit = new Retrofit.Builder()
.baseUrl(Status.HOST_ARTICLE + "content/" + list.get(conversationQueue).conversationId + "/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
ApiService apiService = retrofit.create(ApiService.class);
get_artikel = apiService.artikel();
if like that, i got error
Missing either #GET URL or #Url parameter.
i know in ApiService i must make Parameter "/content/" in Get, but i need make it in proccess class like this
baseUrl(Status.HOST_ARTICLE + "content/" + list.get(conversationQueue).conversationId + "/")
what the best solution for this?
thanks
retrofit = new Retrofit.Builder()
.baseUrl(Status.HOST_ARTICLE + "/" )
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
And
public interface ApiService {
#GET("content/{conversationId}" )
Call<ResponseBody> artikel(#Path("conversationId") String conversationId);
}
Then
apiService.artikel(list.get(conversationQueue).conversationId) ;

Retrofit2 How do i put the / at the end of the dynamic baseUrl?

I have sent and retrieved a url String from a json response using Parcelable in a fragment like so
Received String value
String profile_url = student.getProfile();
I want to use this string value as the basUrl to make another request using Retrofit like so
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(profile_url)
.addConverterFactory(GsonConverterFactory.create())
.build();
But getting the following error
java.lang.RuntimeException: An error occured while executing doInBackground()
......
Caused by: java.lang.IllegalArgumentException: baseUrl must end in /:
How do i put the / at the end of the baseUrl?
Putting it directly like so
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(profile_url/)
.addConverterFactory(GsonConverterFactory.create())
.build();
does not work, Express expected.
Any help. Thanks
Debug Profile url profile_url=http://services.hanselandstudent.com/student.svc/1.1/162137/category/1120/json?banner=0&atid=468f8dc2-9a38-487e-92ae-a194e81809d9
Since you've a complete url to call, you will need the #Url annotation in Retrofit2.
Define your interface with something like that
public interface YourApiService {
#GET
Call<Profile> getProfile(#Url String url);
class Factory {
public static YourApiService createService() {
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl("http://www.what.com/")
.build();
return retrofit.create(YourApiService.class);
}
}
}
Then call it with
YourApiService.createService().getProfile(profile_url);
You must have "/" in the end of your string variable.
String profile_url = student.getProfile() + "/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(profile_url)
.addConverterFactory(GsonConverterFactory.create())
.build();

How to send a retrofit 2 post call with no parameters

I have to call an api using retrofit 2 in android. but with no values. When I does that, it shows that there must be at least 1 #field. Below is the code I am using.
public interface gitAPI {
#FormUrlEncoded
#POST("/MembersWS.svc/GetMemberAvailability/MBR0011581")
Call<Questions[]> loadQuestions();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.99:82")
.addConverterFactory(GsonConverterFactory.create())
.build();
// prepare call in Retrofit 2.0
gitAPI stackOverflowAPI = retrofit.create(gitAPI.class);
Call<Questions[]> call = stackOverflowAPI.loadQuestions();
call.execute();
Declare body value in your interface with next:
#Body RequestBody body and wrap String JSON object:
RequestBody body = RequestBody.create(MediaType.parse("application/json"), (new JsonObject()).toString());

Categories

Resources