Retrofit pass parameter through post and get result - android

This is my Api.php
$command=$_POST["command"];
if($command=="getUsers"){
getUsers();
}
elseif ($command=="getNews")
{
getNews();
}
I'm using retrofit to show result in my android app. I need to pass parameter Command through Retrofit Post and Get a result at the same time.
what's the solution?

Try like this example from Retrofit website:
#FormUrlEncoded
#POST("user/edit")
Call<User> updateUser(#Field("first_name") String first, #Field("last_name") String last);
Source: https://square.github.io/retrofit/

Related

Retrofit 2 removes posrt after special character ":" from base Url

I have an Api https://hello.example.com:344/new/search/result.
Implementing same using Retrofit 2:
This is how initialising retrofit:
public static void initializeRetrofit() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://hello.example.com:344")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
service2 = retrofit.create(ContentService.class);
}
This is the interface request:
#POST("new/search/result")
Call<JsonObject> getSearchList(#Body JsonObject request);
But when i hit api : it removes the port from it and hits
"https://hello.example.com/new/search/result"
What is going wrong?
In your base url "https://hello.example.com:344" transform it to
"https://hello.example.com:344/"
There is no / (slash) in your base url as well as in the interface function. So the request becomes like "https://hello.example.com:344new/search/result " which will give u an error.
Add slash at the end of your base url like this "https://hello.example.com:344/"

How to parse dynamic JSON with Retrofit?

I have dynamic JSON, here is example: http://pastebin.com/QMWRZTrD
How I can parse it with Retrofit?
I failed to generate POJO classes, since I have dynamic fields like "5411" and "5412".
EDIT:
I solved it by using Map, since first value is always integer, and second is list of objects.
#FormUrlEncoded
#POST("history.php")
Observable<Map<Integer, List<Vehicle>>> getHistory(#Field("uredjaji") String vehicleId, #Field("startDate") String startDATE, #Field("endDate")
you can use Map to serialize and deserialize it in case of Random keys.
Observable<Map<Integer, List<YourObject>>>
You can get retrofit api call to return String in your RestApi Interface like
Call<String> method(#Path(..)...);
And for that to work you would need to add the scalars converter factory to where you create your Retrofit object.
First you would need to import it:
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
And then add it:
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://your.base.url/")
.build();
And then in onResponse
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
Type mapType = new TypeToken<Map<String,List<SomeClass>>() {}.getType(); // define generic type
Map<String,List<SomeClass>> result= gson.fromJson(response.body(), mapType);
} else {
}
}
Also,check out this site it has great tutorials on Retrofit.

Retrofit2 - Can't get basic authentication for webAPI with dynamic URL

I'm familiar with how to use dynamic URLs with Retrofit2 but having issue sending username & password in the request. The webAPI works by entering a URL, a login prompt appears on the screen for a username & password, after authentication a JSON response is displayed. The interface is defined for a dynamic URL:
#GET
public Call<User> getJSON(#Url String string);
My request is as follows:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginService service = retrofit.create(LoginService.class);
Call<User> call = service.getJSON("https://username:password#api.url.com/");
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, retrofit2.Response<User> response) {
System.out.println("Response status code: " + response.code());
I'm certain the URL is correct as it works in the browser & but I keep getting error the username & password aren't correct?
I/System.out: Response status code: 401
Also, as far as I can tell I can only use #GET rather than #POST because whenever I try #POST the response code is:
I/System.out: Response status code: 405
At first I tried to follow something similar to this post using an encoded flag because it's an example of how to use #PATH & #URL with Retrofit2 but didn't have any success. That's why I tried the username:password# prepend to the URL. Most of the other examples all use the #POST method.
Any feedback or ideas on how I can authenticate? Thanks
Not sure how to do it in retrofit, but you can add it via an OkHttp interceptor --
OkHttpClient client = new OkHttpClient().newBuilder().addNetworkInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url();
url = url.newBuilder().username("username").password("password").build();
Request newRequest = request.newBuilder().url(url).build();
return chain.proceed(newRequest);
}
}
).build();
be sure to add this client to your retrofit instance --
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Another way to use basic authentication with Retrofit2 would be to pass the authentication string as an argument to your interface method.
So you would change the method signature to:
#GET
public Call<User> getJSON(#Url String string, #Header("Authorization") String myAuthString);
And then call it like this:
Call<User> call = service.getJSON("https://api.url.com/", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Where you substitute QWxhZGRpbjpvcGVuIHNlc2FtZQ== for your Base64-encoded username:password string.
If you need to pass the username and password for every API call and want to keep the method signatures clean, it might be better to use the custom OkHttpInterceptor method instead.

Unable to use Query in retrofit

Hello I am trying to use #Query in retrofit but I am getting error something like this :-
must not have replace block. For dynamic query parameters use #Query.
here is my interface :-
public interface Parser {
#GET("weather?q={city}&appid=0a8")
Call<Model> getModel(#Query("city") String city);
}
And this is in my Activity :-
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("xyz/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Parser parser = retrofit.create(Parser.class);
Call<Model> call = parser.getModel("london");
Thanks in advance
if your api query should be like -
BASE_URL/weather?q=london&appid=0a8
Then use
#GET("weather")
Call<Model> getModel(#Query("q") String city,#Query("appid") String app_id);
In this case you should use #Path instead of #Query
public interface Parser {
#GET("weather?q={city}&appid=0a8")
Call<Model> getModel(#Path("city") String city);
}

How #PUT some value in webservice via Retrofit

I wanna send a list of integer with userName and password to WebService some thing like bellow request
UpdateDocumentState(List<int> documentIds, string userName, string password)
But I don't know How to do that ? Use #Post Or #Put ? use #Query Or #Field ? I googled but didn't find any good example or tutorial which explained these well. ( All tutorial I found was about #GET )
could anyone give me some piece of code , how to do that ?
About the use of #PUT or #POST I think you had to get this information from the WebService developers.
Anyway, here sample code for both of Retrofit annotations with or without Callback response.
#POST("your_endpoint")
void postObject(#Body Object object, Callback<Response> callback);
#PUT("/{path}")
String foo(#Path("path") String thePath);
EDIT:
Object is a custom class which represent the data you had to send to the WebService.
public class DataToSend {
public List<Int> myList;
public String username;
public String password;
}
For example when the #POST annotation declaration will be:
#POST
void postList(#Body DataToSend dataToSend, Callback<Response> callback);
and then you call the method using Retrofit service
yourService.postList(myDataToSend, postCallback);

Categories

Resources