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/
Related
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.
I'm writing a library for a REST API. The library will have to hide to the user the internal complexity of the API as much as possible.
I'm relying on retrofit2 configured to use RxJava to wrap the responses and GSon to parse them.
I'm using retrofit for a REST service.
#GET("search")
Observable<SearchResult> search(#Query("q") String query);
#GET("search")
Observable<SearchResult> search(#QueryMap Map<String, String> params);
#GET("search")
Observable<SearchResult> searchNext(#Query("q") String query, #Query("startKey") String startKey);
#GET("search")
Observable<SearchResult> searchNext(#QueryMap Map<String, String> params, #Query("startKey") String startKey);
The search REST service return a JSON
{
"count": 2334,
"nextBatchKey": "SADjdfsahoi023451sadfjlskdfj02134512",
"results": [ .... ]
}
the total count of result
a key to be used to retrieve the next batch of the list
the actual array of results
To obtain the next batch the service has to be called again with the same parameters and the key returned.
For example, suppose doing a search for q=foo and limit=20: the REST API will return the results matching string foo batched in segments for 20 results each. To get the next batch I would need to create another request with the same two parameters, q=foo and limit=20, adding startKey=<the next batch key>.
I want / need to hide from the user of the library these internal mechanism.
Inside my library I initialize retrofit like this:
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient) // added interceptors
.baseUrl(baseUrl) // my base url
.addConverterFactory(GsonConverterFactory.create(gson)) // custom type adapter factory
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
It generate the service for my interface and use Gson to parse the response wrapping it with RxJava Observable.
Then I obtain the service:
MyService service = retrofit.create(MyService.class)
Note that I do not write the code of this service, as retrofit works it generate the service automatically using my interface (MyService) annotations.
From the library user perspective all this is hidden, he will just receive the service and use it like this:
// obtain the service
MyService service = MyLibrarySDK.getService(context);
// perform the search operation
Observable<SearchResult> resultObservable =
service.search(params);
I want the developer using my library to be able to get the next batch like this:
// then later result == the SearchResult
Observable<SearchResult> nextBatch =
result.searchNext();
The searchNext() call takes no parameters. This means the SearchResult object I created in the previous call should internally know which parameters to use when using the method searchNext(Map parameters, String key).
If the user perform the search call with q=foo this information is not received in the response. And I need it.
Since retrofit create the service I don't know how I can intercept the method parameters passed with the call to service.search().
The only idea I had to address this is to use an OkHttp interceptor, place the query parameters map in a ThreadLocal, then use a custom Gson TypeAdapter to inject those parameters into the SearchResult object.
This solution should technically work but I think it's ugly. Furthermore the interceptor would run for any method of the REST API but I need it only for search queries.
Have you got a better / creative / elegant idea?
Don't think you should have have searchNext() on the result but rather on the service.
Try something like below:
MyService.java
public class MyService {
RestClient.GitApiInterface service = RestClient.getClient();
String query;
Observable<GitResult> resultObservable;
public Observable<GitResult> getUsersByName(String query) {
this.query = query;
resultObservable = service.getUsersByName(query, 0).cache();
return resultObservable;
}
public Observable<GitResult> searchNext() {
Observable nextResultObservable = resultObservable
.flatMap(new Func1<GitResult, Observable<?>>() {
#Override
public Observable<?> call(GitResult gitResult) {
return service.getUsersByName(query, gitResult.getNextPage());
}
});
return nextResultObservable;
}
}
Usage
final MyService service = new MyService();
// First load
service.getUsersByName("tom");
// consecutive calls
service.searchNext();
Sample app - https://gitlab.com/wizardkrishna/retrofit2-sample
References
Consuming REST API using Retrofit2
Observable Caching
I am using Retrofit in android and GsonConverterFactory is converter.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://xxxxxxx.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
I want send POST request with body.
public class MasterRequest
{
}
public class User extends MasterRequest
{
#SerializedName("email")
public String email = null;
}
#POST("{path}")
Call<MasterResponse> registerUser(#Path("path") String path, #Body MasterRequest masterRequest);
path is the URL that append with base URL.
When ever I send child class("User") object in parent class reference(MasterRequest), then converter shown empty json; "{}".
But when I send User class object to below registerUser Method, then it working fine.
#POST("{path}")
Call<MasterResponse> registerUser(#Path("path") String path, #Body User user);
How can I send child class object in parent class instance to make request body?
That's how Gson works. The easiest way to serialize polymorphic objects is use RuntimeTypeAdapterFactory. You can find detailed tutorial here. Works great with Retrofit!
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 use android annotations to communicate with the server. In one of the api calls I need to send some text data and an image, say, from gallery.
#Post("/items/addItem.php")
String addItem(Protocol protocol);
How do I attach a MultipartForm with an image along with the post request?
Just use the right Spring converter : FormHttpMessageConverter.
However, this converter only accepts MultiValueMap as method parameter. Please have a look at these two issues: #652 and #660.
If you really want to use any object as parameter, you have to implement your own custom FormHttpMessageConverter which will handle that by using reflection.
DayS is right. An as quotation, you must include the FormHttpMessageConverter in your Rest Interface definition inside the converters array:
#Rest(rootUrl = "http://api.yourapp.com", converters = {
MappingJacksonHttpMessageConverter.class,
StringHttpMessageConverter.class, FormHttpMessageConverter.class })
public interface YourAppApiClient {
#Post("/items/addItem.php")
void getCustomerInformation(MultiValueMap formfields);
}
-Totaly Agree with above answers but for use of mappinjacksonhttpmessageconverter you have to add another library so if you dnt want to use it you can use below example
Or you can consider it as another example also :)
#Rest(rootUrl = CommonUtils.BASE_URL, converters = { ByteArrayHttpMessageConverter.class,
FormHttpMessageConverter.class, StringHttpMessageConverter.class })
public interface CustomRest extends RestClientErrorHandling{
#Post(CommonUtils.pUrlLogin)
String _Login(MultiValueMap<String, Object> multiValueMap);
#Post(CommonUtils.pUrlSignUp)
String _SignUp(MultiValueMap<String, Object> multiValueMap);
}