I have webservices hosted on server but I am using retrofit to fetch data from the server but When I am running my app it is showing exception Unresolve host but when I am using the same Url in Postman and browser it is working fine.I have also add Internet permission in app manifest file.
Below is my code:
RetrofitClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getInstance(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(22, TimeUnit.SECONDS)
.readTimeout(22, TimeUnit.SECONDS)
.writeTimeout(22, TimeUnit.SECONDS)
.build();
if(retrofit == null)
retrofit = new Retrofit.Builder()
.baseUrl("https://adbhutbharat.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
}
ApiService.java
public interface ApiService {
#GET("app/getAgents.php")
Call<List<Agents>> allAgents();
}
The above endpoint is working properly in postman and browser but not when requesting using retrofit in android to fetch data.
Someone please let me know how to resolve this error any help would be appreciated.
THANKS
Related
I found something strange when I add interceptor like this:
public ApiDefinition getService() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
System.out.println("into interceptor");
Request request = chain.request();
return chain.proceed(request);
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
return retrofit.create(ApiDefinition.class);
}
Then when I do call a network, nothing print just like the interceptor did't work.
Observable observable = apiDefinition.getResponse();
observable.subscribe(....)
I am confused, was there anything wrong?
apiDefinition.getResponse(); you forgetting to subscribe api call. Just getting observable, but not observing it.
apiDefinition
.getResponse()
.subscribe(.......);
if you want to intercept Network request call and print them in logcat
you can do so by adding an HttpLoggingInterceptor like that:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
Sorry guys, i make some mistakes when i user dagger2 to inject ApiDefinition, so this is solved.
Using android retrofit, I'm having problems referring to my url.
Either of these are ok to use:
http://www.example.com/foo.asmx/dostuf
Or
http://www.example.com/foo.ashx?r=dostuff
The examples I've seen indicate:
http://www.example.com/post
What file is that processing?
So, how to I implement my url?
Thanks
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("Your Url")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
I've got it.
Here it is to help out others...
The BASE url goes here:
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.example.com/").build();
The ENDPOINT url goes here:
public interface retrofit_post1 {
#POST("example.ashx?r=dostuff")
Call<ResponseBody> update(#Body RequestBody requestBody);
}
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().
guys.Recently,I have a problem.I am using Retrofit + okhttp to do the network. But now I have to encrypt all the parameters,since I have Chinese in the parameters,it will be encoded before interceptor,so for those apis,i have to do something special。I think it's not a good idea,.so is there any solution to encrypt the parameters before it's been encoded?
I have solved my problem by creating a new Call to replace the orginal one like below. hope to help some one like me.
final OkHttpClient okHttpClient = CustomHeaderOkHttpClient.newInstance()
.newBuilder()
.build();
Retrofit retrofit = RetrofitUtils.createGsonRxJavaRetrofitBuilder()
.client(okHttpClient)
.callFactory(new Call.Factory() {
#Override
public Call newCall(Request request) {
Request encryptRequest = EncryptCallHelper.encryptRequest(request);
return okHttpClient.newCall(encryptRequest);
}
})
.baseUrl(sBaseUrl)
.build();
CustomHeaderOkHttpClient is just an instance of OkHttp like blow.
public class CustomHeaderOkHttpClient {
public static OkHttpClient.Builder newBaseBuilder(Context context) {
return new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.cookieJar(new WebViewCookieJar())
;
}
}
the EncryptCallHelper I cannot paste here ,I am so sorry. the content works like this:
get all params with the request
encrypt your params in your own way
return the new Call to Retrofit
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.