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
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.
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
I'm using Retrofit 2, I want to know the values or Structure of sending the value to the server. Is there any way where can I put 'system.out.print' so that I can know what Am I sending?
first add this
impletemtaion "com.squareup.okhttp3:logging-interceptor:LATEST_VERSION";
add this
#Provides
#Singleton
public OkHttpClient provideClient(Context mContext, CacheInterceptor cacheInterceptor, HeaderInterceptor headerInterceptor) {
//***************
HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
logger.setLevel(HttpLoggingInterceptor.Level.BODY);
//***************
return new okhttp3.OkHttpClient.Builder()
.addInterceptor(logger)
.addInterceptor(headerInterceptor)
.connectTimeout(Constant.CONNECTTIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constant.READTIMEOUT, TimeUnit.SECONDS)
.writeTimeout(Constant.WRITETIMEOUT, TimeUnit.SECONDS)
.build();
}
Refer to this for HTTPLogging Interceptor for Retrofit 2
https://futurestud.io/tutorials/retrofit-2-log-requests-and-responses
I am facing the issue of socket timeout exception while using retrofit 2.0.2 library and okhttp 2.3.0. I am trying to upload the image file which is between 500kb to 1.5mb it is uploading successfully.but when i tried to upload video file which is greater than 5mb i am getting this exception.
I used httpclient for connection settings as below.
public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(0, TimeUnit.SECONDS)
.writeTimeout(0, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.SECONDS)
.build();
please suggest me to upload larger files without this issue.Thanks in advance
you can provide the time in seconds as follows
public class ApiClient {
public static final String BASE_URL = "your_url";
public static Retrofit retrofit = null;
public static Retrofit getApiClient() {
if (retrofit == null) {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
i've given 60 seconds
There can be two issues with this type of error.
Check Read & Write Timeout
val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
Check the Mime type you are sending. The backend developer may have filtered the accepted Mime type at their end. instead of MediaType.parse("multipart/form-data"). write the valid mime type for files like image/jpg or video/mp4
MediaType.parse("image/png")
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.