how to call Retrofit GET method api in which no value will pass in GET(")
this is my code
#GET(" ")
fun fetchData(): Call<List<Data>>
this is my BASE URL https://abhi-debug.github.io/Caption/All
and it cant have backslash at end
#GET(".")
fun fetchData(): Call<List<Data>>
Pass "." as the parameter
My suggestion would be to have a base URL like: https://abhi-debug.github.io/
And then add this:
#GET("Caption/All")
fun fetchData(): Call<List<Data>>
Solution 1
You can use #GET(".") to indicate that your url is the same as the base url.
#GET(".")
Call<List<Data>> fetchData();
Solution 2
You can pass URL to reuest as you mention you got URL in json response
#GET()
Call<List<Data>> fetchData(#Url String url);
and call
Call<List<Data>> call = retrofitInterface.fetchData("https://abhi-debug.github.io/Caption/All");
call.enqueue(new Callback<List<Data>>() {
#Override
public void onResponse(Call<List<Data>> call, Response<List<Data>> response) {
Log.i(TAG, response.body().toString());
List<Data> body = response.body();
Log.i(TAG, body.get(0).getId()+"");
}
#Override
public void onFailure(Call<List<Data>> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
In your Api Interface use this method
#GET
Call<JsonObject> fetchData(#Url String config);
Related
When I Type Base Url="https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/" with last slash(/) then give me message like this:
Response{protocol=http/1.1, code=500, message=Internal Server Error, url=https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/?user=XX&pass=r#12&msisdn=0160000000&trxid=6BM3KRWHLB}
After "sendmsg" slash(/) does not need
And When I Type Base Url="https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg" with out last slash(/) then apps unfortunately stop;
For this I Want to remove last "/" any way from Base Url.
private void requestDataForBkashTransaction() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/")
.addConverterFactory(GsonConverterFactory.create())
.build();
InstituteService api = retrofit.create(InstituteService.class);
String urlString=String.format("?user=Exampll&pass=12345&msisdn=0160000000&trxid=6BM3KRWHLB");
Call<List<Transaction>> call=api.getBkashTrasactionCode(urlString);
call.enqueue(new retrofit2.Callback<List<Transaction>>() {
#Override
public void onResponse(Call<List<Transaction>> call, retrofit2.Response<List<Transaction>> response) {
if(!response.isSuccessful()){
Toast.makeText(PaymentActivity.this, response.code(), Toast.LENGTH_LONG).show();
return;
}
List<Transaction> transactions=response.body();
for(Transaction transaction:transactions){
String content="";
content+=transaction.getTrxId();
textView.append(content);
}
}
#Override
public void onFailure(Call<List<Transaction>> call, Throwable t) {
}
});
}
#GET
Call<List<Transaction>> getBkashTrasactionCode(#Url String url);
This is not how you add query parameters to a call using retrofit. Response code 500 Internal Server Error indicates that. Please refer to this this and add queries properly, then it should work.
To remove last slash,
you have to remove last path from the baseUrl with ../ first, then append it at your urlStirng instead.
String urlString=String.format("../sendmsg?user=Exampll&pass=12345&msisdn=0160000000&trxid=6BM3KRWHLB");
First assign your baseUrl to a String variable and remove the last character as below.
String baseUrl = "https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/";
if (baseUrl.endsWith("/")) {
String newBaseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}
I'm still beginner on retrofit API for android, im trying to pass a variable into my dynamic url but it adds extra characters to it these characters are "&=".
This is what the endpoint im trying to consume looks like:
https://www.example.com/api/index.php?/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/9392
where "9232" is the id i am trying to pass. However when i use the retrofit library this is what my generated Url looks like:
https://www.example.com/api/index.php?/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/&=9392
Notice the &= being attached to the Id im sending
// Method that receives id and calls the retrofit API
private void getPlaylist(String id) {
/*Create handle for the RetrofitInstance interface*/
GetPlaylistRetrofitInterface playlistService = PlaylistClientInstance.getRetrofitInstance().create(GetPlaylistRetrofitInterface.class);
Call<List<Playlists>> call = playlistService.getPlaylist(id);
Log.d("URL", "getPlaylist: " + call.request().url());
call.enqueue(new Callback<List<Playlists>>() {
#Override
public void onResponse(Call<List<Playlists>> call, Response<List<Playlists>> response) {
myProgressBar.setVisibility(View.GONE);
populatePlayList(response.body());
}
#Override
public void onFailure(Call<List<Playlists>> call, Throwable throwable) {
myProgressBar.setVisibility(View.GONE);
Log.d("onFailure", "onFailure: " + throwable);
Toast.makeText(getActivity(), throwable.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
And this is the interface where i am receiving the url id and attaching it to the endpoint
public interface GetPlaylistRetrofitInterface {
#GET("index.php?/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/")
Call<List<Playlists>> getPlaylist(#Query(value = "") String id);
}
I have tried using #Path in my interface
public interface GetPlaylistRetrofitInterface {
#GET("index.php?/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/{id}")
Call<List<Playlists>> getPlaylist(#Path("id") String id);
}
However it made my app crash with this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.demoapp.HomeActivity}:
java.lang.IllegalArgumentException: URL query string "/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/{id}" must not have replace block. For dynamic query parameters use #Query.
for method GetPlaylistRetrofitInterface.getPlaylist
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Thanks in Advance
Okay so i was able to Fix the issue, I turned out i was trying to pass a query by using #Query to an endpoint which is already a query so this is how i fixed it:
This is my updated GetPlaylistInterface
public interface GetPlaylistRetrofitInterface {
#GET()
Call<List<Playlists>> getPlaylist(#Url String url);
}
This is my updated Get Playlist method
private void getPlaylist(String id) {
myProgressBar.setVisibility(View.VISIBLE);
/*Create handle for the RetrofitInstance interface*/
GetPlaylistRetrofitInterface playlistService = RetrofitClientInstance.getRetrofitInstance().create(GetPlaylistRetrofitInterface.class);
Call<List<Playlists>> call = playlistService.getPlaylist(Config.playlist_url+id);
Log.d("URL", "getPlaylist: " + call.request().url());
call.enqueue(new Callback<List<Playlists>>() {
#Override
public void onResponse(Call<List<Playlists>> call, Response<List<Playlists>> response) {
myProgressBar.setVisibility(View.GONE);
populatePlayList(response.body());
}
#Override
public void onFailure(Call<List<Playlists>> call, Throwable throwable) {
myProgressBar.setVisibility(View.GONE);
Log.d("onFailure", "onFailure: " + throwable);
Toast.makeText(getActivity(), throwable.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
And this is the config class containing the endpoints:
public class Config {
public static String playlist_url = "index.php?/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/";
public static String playlist_details_url = "index.php?/Tracks/get/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/";
}
You're using #Query parameter, which has this syntax by default.
What your need is to use #Path instead of #Query. Also you need to include name of parameter into your url string.
Your code will look somehow like this:
public interface GetPlaylistRetrofitInterface {
#GET("index.php?/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/{id}")
Call<List<Playlists>> getPlaylist(#Path("id") String id);
}
You almost Have it first You need to use Query Parameter for you query String and Path for url/uri manipulation seems like you had those mixed up now below example should work
public interface ApiServices {
#GET("index.php?/Playlists/getTracks/00978d67f6933af10ec8bd8045f089a4/0673CC13-476A-4786-BF27-13ADD9C44261/{id}")
Call<ResponseBody> getTracks(#Path("id") String id);
}
EDIT:
You need to only define Interface and call it once. Above is interface and below is how to call it from a functions like your trying to do... its weird you have index.php? are you sure that is needed.
// Method that receives id and calls the retrofit API
private void getPlaylist(String id) {
/*Create handle for the RetrofitInstance interface*/
OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://stepank.com/")
.build();
ApiServices service = retrofit.create(ApiServices.class);
try {
Call<ResponseBody> call = service.getTracks(id);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
int result = -1;
setRefreshActionButtonState(false);
if (response.isSuccessful()) {
///DO STUFF HERE WITH RESPONSE
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
URL query string "q={city}" must not have replace block
I can't get this to work, I've tried several other variants but still get some form of exception.
public interface WeatherInterface {
#GET("/weather?q={city}")
Call<WeatherModel> getWeather(#Query("city") String city);
}
/////
public interface WeatherInterface {
#GET("/weather")
Call<WeatherModel> getWeather(#Query("q") String city);
}
And so on.
WeatherActivity.class
Call<WeatherModel> call = weatherInterface.getWeather("""CITYNAME""");
call.enqueue(new Callback<WeatherModel>() {
#Override
public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
if(response.isSuccessful()) {
**///FIRST VARIANT FAILS HERE**
city.setText(response.body().getName());
}
**///SECOND VARIANT FAILES RESPONSE**
else Log.d("No response", "RESPONSE");
}
#Override
public void onFailure(Call<WeatherModel> call, Throwable t) {
Log.d("fail", "fail");
}
});
EDIT:
Log.d(call.request().url().toString(), "CALL REQUEST URL");
I should share my solution too probably, I just logged the call url.
I forgot the to add my API KEY in the url. I shamefully withdraw my question.
U can use this sample take example:
public interface GitHubClient {
#GET("/users/{user}/repos")
Call<List<GitHubRepo>> reposForUser(
#Path("user") String user
);
}
For more samples just visit this website
I am making a weather app by using the wunderground API. I am also using Retrofit2 and GSON library.
Here is the API URL format to get the JSON response:
http://api.wunderground.com/api/API_KEY/conditions/q/ISO_COUNTRY_CODE/CITY_NAME.json
I've declared an java API_Interface as follows:
public interface API_Interface {
#GET("/api/{apikey}/conditions/q/BD/{city}.json")
Call<CurrentObservation> getCurrentWeather(
#Path("apikey") String apikey,
#Path("city") String city);
}
And trying to pass the apikey and city from the MainActivity as follows:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
API_Interface weatherService = retrofit.create(API_Interface.class);
Call<CurrentObservation> call = weatherService.getCurrentWeather(Constants.API_KEY,"Dhaka");
call.enqueue(new Callback<CurrentObservation>() {
#Override
public void onResponse(Call<CurrentObservation> call, Response<CurrentObservation> response) {
textView.setText(response.body().toString());
Log.d("result",response.body().toString());
}
#Override
public void onFailure(Call<CurrentObservation> call, Throwable t) {
textView.setText("Something went wrong: " + t.getMessage());
Log.e("error",t.getMessage());
}
});
Here is the Constant class:
public class Constants {
public static final String BASE_URL="http://api.wunderground.com";
public static final String API_KEY="b5efba6dc63cc1b1";
}
and here is the POJO Model of CurrentObservation class: http://paste.ubuntu.com/22291964/
I've overriden a toString() method in the model.
There are some other POJO classes-
But this approach gives null response as following-
Weather Status: null
Pressure: null
Humidity: null
Temperature: null
Here is the actual JSON response from the API URL- http://paste.ubuntu.com/22292683/
How do I pass the parameters into #GET to get the correct response?
Your base URL should look like this:
http://blah.com/api/blah/
And your #GET method should have an URL like this
api/{apikey}/conditions/q/BD/{city}.json
EDIT: You might have onResponse called with an error body. Please adjust the following code for your use-case:
public static boolean handleError(Retrofit retrofit, Response<?> response) {
if(response != null && !response.isSuccessful() && response.errorBody() != null) {
Converter<ResponseBody, ErrorResponse> converter = retrofit.responseBodyConverter(ErrorResponse.class, new Annotation[0]);
try {
ErrorResponse errorResponse = converter.convert(response.errorBody());
// do something
} catch(IOException e) {
Log.e(TAG, "An error occurred", e);
}
return true;
}
return false;
}
You can do it like that:
#GET
Call<CurrentObservation> getCurrentWeather(#Url String url);
I am an iOS Developer starting to learn Android. In Swift, creating a completion handler is very simple, but I still can't find a way to do it in Java.
I am sorry if this question is too noob for StackOverflow people.
Problem
I am creating a class to handle all my Http Request which is done using Retrofit.
I make this function is my RequestHelper.java
public static void checkEmailAvailability(String email) {
MyWebServiceAPI serviceAPI = retrofit.create(MyWebServiceAPI.class);
Call<APIResults> call = serviceAPI.checkEmailAvailability(getAuthenticationHeader(), RequestBody.create(MediaType.parse("text/plain"), email));
call.enqueue(new Callback<APIResults>() {
#Override
public void onResponse(retrofit.Response<APIResults> response, Retrofit retrofit) {
//Parse Response Json
//Get some value and place it inside an object
//ANDI WOULD LIKE RETURN SOME BOOLEAN VALUE AND SOME OTHER STRING
}
#Override
public void onFailure(Throwable t) {
//I WOULD LIKE A BOOLEAN VALUE HERE
}
});
}
I call it like this from my MainActivity
RequestHelper.checkEmailAvailability("user#user.com");
Now the function is still void but I would like for it to return something after the on the onResponse and onFailure method.
Any thoughts please?
You should pass the Callback object as a parameter to the checkEmailAvailability().
And implement the interface when you call the method from your MainActivity,and use the response parameter in the onXXX() method as the data returned to update UI.