I want know if I can use Retrofit with this type of url:
https://example.com/mobile_api.php?action=test
if I try to use Retrofit with a Base Url without the slash at the end of the url I get an Exception, my url is this:
https://example.com/mobile_api.php
not this:
https://example.com/mobile_api.php/
How I can do?
Maybe this can help.
Retrofit 1
#GET("/path/to/api/mobile_api.php")
void getAction(#Query("action") String action, Callback<YourCallBack> response);
Retrofit 2
#GET("/path/to/api/mobile_api.php")
Call<YourCallBack> getAction(#Query("action") String action);
Make an interface something like this
#GET("mobile_api.php")
void doSomeAction(#Query('action')String action, Callback<YourResponseClass> callback);
and then call this with your Restclient instance.
Related
While studying Retrofit Library I cae across API Interface I could not understand the Code/terms used inside it. Can anyone explain the lines of code??
public interface ApiInterface {
// For POST request
#FormUrlEncoded // annotation that used with POST type request
#POST("/demo/login.php") // specify the sub url for our base url
public void login(
#Field("user_email") String user_email,
#Field("user_pass") String user_pass, Callback<SignUpResponse> callback);
//user_email and user_pass are the post parameters and SignUpResponse is a POJO class which recieves the response of this API
// for GET request
#GET("/demo/countrylist.php") // specify the sub url for our base url
public void getVideoList(Callback<List<CountryResponse>> callback);
// CountryResponse is a POJO class which receives the response of this API
}
Thanks For any Response!!
Hi is there any simple way to use retrofit with recyclerview to fetch json parser from my online website . So far i used Okhttp to get data from local server.A detailed answered will be really appreciated.Thanks in advance.
This tutorial may definitely help you to load json to listview.
https://www.simplifiedcoding.net/retrofit-android-tutorial-to-get-json-from-server/
For recyclerview, follow this link
https://www.learn2crack.com/2016/02/recyclerview-json-parsing.html
first of all copy the response of your API and create your bean classes through
this site
* By clicking source type to JSON
* Annotation Style to GSON
* Unticking useDoubleNumbers
* Unticking AllowAdition Property
then copy those files to your project
Define your base Url in your Class.
make a interface named ApiController, there declare your API as
#FormUrlEncoded
#POST("your api link excluding the base url")
Call<Bean> callApi(#Field("your parameters") String name);
then in your activity write code
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiController apiController = retrofit.create(ApiController.class);
Call<Bean> result = apiController.callApi("your parameter");
result.enqueue(new Callback<Bean>() {
#Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
}
#Override
public void onFailure(Call<Bean> call, Throwable t) {
}
});
Retrofit 2.0 GET and POST method
The link will gudie to learn the methods of retrofit2.0 for GET and POST method.
http://www.iayon.com/consuming-rest-api-with-retrofit-2-0-in-android/
You can learn retrofit to pass JsonArray and JsonObject in the following link
https://www.androidtutorialpoint.com/networking/retrofit-android-tutorial/
I receive (Step 1) a soapString from a server and I would like to forward (Step 2) this String to another server.
public interface StepTwoRestAdapter {
#Headers({"Content-Type:text/xml"})
#POST("/services/step2/forwardSoap")
Observable<String> order(#Body SoapString soapString);
}
In this case above, the afgter my.server.com which is "/webservices/step2/forwardSoap" is constant always. How can I make this part variable?
The trick here is, that the second server (for step 2) is specified in the response of the first reponse.
EDIT:
Now, I use the proposal from #Tabish Hussain
public interface StepTwoRestAdapter {
#Headers({"Content-Type:text/xml"})
#POST("/{urlPath}")
Observable<String> order(#Body SoapString soapString, #Path("urlPath") String urlPath);
}
and then I call
restAdapter.create(StepTwoRestAdapter.class).order(new TypedString(soapString), uriPath)
whereas my uriPath is "services/step2/forwardSoap"
But retrofit then calls:
https://my.server.com/services%2Fstep2%2FforwardSoap
As you can see '/' was replaces by "%2F"
Do it like this
public interface StepTwoRestAdapter {
#Headers({"Content-Type:text/xml"})
#POST("/services/{soapString}/forwardSoap")
Observable<String> order(#Path("soapString") SoapString soapString);
}
Check this links, you should be able to find answer there:
https://futurestud.io/tutorials/retrofit-2-how-to-use-dynamic-urls-for-requests
https://futurestud.io/tutorials/retrofit-2-how-to-change-api-base-url-at-runtime-2
I think the easiest way is:
public interface StepTwoRestAdapter {
#Headers({"Content-Type:text/xml"})
#POST
Observable<String> order(#Url String url, #Body SoapString soapString);
}
If you are using Retrofit 1 check this one:
https://medium.com/#kevintcoughlin/dynamic-endpoints-with-retrofit-a1f4229f4a8d#.7atwl0o3t
This question already has answers here:
Unable to create call adapter for class example.Simple
(19 answers)
Closed 7 years ago.
I am trying to get response from the following Api :
https://api.github.com/users/username
But I don't know how to get response as String so that I can use the String to parse and get the JSONObject.
Retrofit version used:
retrofit:2.0.0-beta1
I have tried this until now:
public interface GitHubService {
#GET("/users/{user}")
public String listRepos(#Path("user") String user,Callback<String> callback);
}
retrieving :
GitHubService service = retrofit.create(GitHubService.class);
service.listRepos("username", new Callback<String>() {
#Override
public void onResponse(Response response) {
System.out.println(response.toString());
}
#Override
public void onFailure(Throwable t) {
}
});
exception:
Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class java.lang.String. Tried:
* retrofit.ExecutorCallAdapterFactory
at retrofit.Utils.resolveCallAdapter(Utils.java:67)
at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:49)
Any help would be really appreciated.
** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
#GET("/users/{user}")
Call<String> listRepos(#Path("user") String user);
}
Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with #CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --
public interface GitHubService {
#GET("/users/{user}")
Call<ResponseBody> listRepos(#Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.
I am using Retrofit to Post form data and recieve back XML. What I have so far works fine but i want to make some changes. Here is my existing code (and it works):
Here is my interface
public interface SignupUser
{
#FormUrlEncoded
#POST("/createaccount.cfm")
SignupServerResponse signup(#Field("e") String email, #Field("p") String password);
}
Here is the code to call the api (again, this works fine, I will explain below what I want to change)
SignUpDetails mDeets; // this gets initialize and set somewhere else
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://myurl.com")
.setConverter(new SimpleXMLConverter()).build(); // the response is xml, that works fine
SignupUser service = restAdapter.create(SignupUser.class);
SignupServerResponse res = service.signup(mDeets.getE(), mDeets.getP());
How can I make it so that I can pass the SignUpDetails object straight to the signup() method instead of passing in separate Strings? When I change the constructor of signup() to accept SignUpdetails object (see below) and pass my SignUpDetails object in, I get an error saying
No Retrofit Annotation Found
Here is how I would like to define the interface
public interface SignupUser
{
#FormUrlEncoded
#POST("/createaccount.cfm")
SignupServerResponse signup(SignUpDetails deets);
}
And call it like this (instead of passing in all those parameters)
SignupServerResponse res = service.signup(mDeets);
I tried adding #Field above each of my variables in the SignUpDetails class and that doesnt work either (compilation error)
On your interface use #Body annotation for the deets parameter:
#POST("/createaccount.cfm")
SignupServerResponse signup(#Body SignUpDetails deets);
That should convert SignUpDetails into XML (since you use xml converter on your adapter).
It is then your responsibility to parse the XML request body on server.