How to send a retrofit 2 post call with no parameters - android

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());

Related

Retrofit: Raw response body from a gson converted body

I am using the following libraries for retrofit.
'com.squareup.retrofit2:retrofit:2.5.0'
'com.squareup.okhttp:okhttp:2.7.5'
'com.squareup.retrofit2:converter-gson:2.5.0'
'com.squareup.okhttp3:logging-interceptor:3.10.0'
How can I get the raw response in onResponse callback? I already searched for it and got a lots of solutions which doesn't help now. I tried response.raw().body.string() and response.body().source().toString() which throws can not read body from a converted body. I also tried response.body().string() but in this case .string() is unresolved. I can log the response using interceptor but I need that response in my onResponse() callback, not just printing in logcat.
My Retrofit Client:
public static ApiService getClient(Context context) {
if (retrofit == null) {
if (BuildConfig.FLAVOR.equalsIgnoreCase("dev")){
retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(okHttpClient)
.build();
}else {
retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(SelfSigningClientBuilder.createClient(context))
.build();
}
}
return retrofit.create(ApiService.class);
}
My Retyrofit Interface:
#retrofit2.http.POST("weekly_driver_earning_report/")
#retrofit2.http.FormUrlEncoded
Call<List<DailyEarnings>> getDriverWeeklyEarnings(#retrofit2.http.Field("access_token") String access_token, #retrofit2.http.Field("start_date") String start_date, #retrofit2.http.Field("end_date") String end_date);
Following this, I solved my problem later. I defined my Call type to specific model class and that's why response.body().string() was inaccessible, Changing my Call type from List to ResponseBody, I could access response.body().string().

Make more #path in Retrofit URL

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);

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();

Retrofit 2 check call URL

Is there any possibility to compare a Call URL with a String in Retrofit 2?
For example we can take this baseUrl:
https://www.google.com
And this Call:
public interface ExampleService {
#GET("dummy/{examplePartialUrl}/")
Call<JsonObject> exampleList(#Path("examplePartialUrl") String examplePartialUrl;
}
with this request:
Call<JsonObject> mCall = dummyService.exampleList("partialDummy")
There's a way to obtain https://www.google.com/dummy/partialDummy or also dummy/partialDummy before getting the response from the call?
Assuming you're using OkHttp alongside Retrofit, you could do something like:
dummyService.exampleList("partialDummy").request().url().toString()
which according to the OkHttp docs should print:
https://www.google.com/dummy/partialDummy
Log.d(TAG, "onResponse: ConfigurationListener::"+call.request().url());
Personally I found another way to accomplish this by using retrofit 2 and RxJava
First you need to create an OkHttpClient object
private OkHttpClient provideOkHttpClient()
{
//this is the part where you will see all the logs of retrofit requests
//and responses
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient().newBuilder()
.connectTimeout(500, TimeUnit.MILLISECONDS)
.readTimeout(500,TimeUnit.MILLISECONDS)
.addInterceptor(logging)
.build();
}
after creating this object, the next step is just use it in retrofit builder
public Retrofit provideRetrofit(OkHttpClient client, GsonConverterFactory convertorFactory,RxJava2CallAdapterFactory adapterFactory)
{
return new Retrofit.Builder()
.baseUrl(mBaseUrl)
.addConverterFactory(convertorFactory)
.addCallAdapterFactory(adapterFactory)
.client(client)
.build();
}
one of the attributes you can assign to Retrofit builder is the client, set the client to the client from the first function.
After running this code you could search for OkHttp tag in the logcat and you will see the requests and responses you made.

Retrofit 2.0 beta 1 with whole URL

In retrofit 2.0 i want to use only one url .The url is same as base url as that of #GET in interface.I am facing the problem for getting the response.If Any one have better solution for using the whole url in #GET then please suggest the solution.
here is the code
public class RestClient {
private static ApiInterface apiInterface ;
private static String baseUrl = "here is my whole base url";
public static ApiInterface getClient() {
if (apiInterface == null) {
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverter(String.class, new ToStringConverter())
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiInterface = client.create(ApiInterface.class);
Log.e("RETROFIT RESPONCE IS...", client.toString());
}
return ApiInterface ;
}
public interface ApiInterface {
#Headers("User-Agent: Retrofit2.0Tutorial-App")
#GET("here is my whole base url”)
Call<EventResult> getEvent();
}
}
With retrofit 2 is possible to use the #Url annotation. Let's assume your Retrofit configuration is
Retrofit builder = new Retrofit.Builder()
.baseUrl("http://wwww.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
Test r = builder.create(Test.class);
you declare your interface:
public interface Test {
#GET
Call<Example> getTest(#Url String url);
}
and for getTest you don't want to use the baseUrl you declared in the configuration. The #Url will ignore the baseUrl you declared and will use the one you provide as argument
I don't think it's possible since BaseURL is mandatory in Retrofit Builder and even you supply the builder with the full URL the builder will parse it and save only the BaseURL. I guess the reason why they do this is to keep it simple and consistent.
for reference you can see the source code here

Categories

Resources