I am trying to send Json with formated Date (pattern="yyyy-MM-dd HH:mm:ss").The problem is that server don't recognize this pattern and give error java.io.EOFException: \n not found: limit=1 content=0d… I tried add GsonBuilder in RetrofitClient class, but it doesn't worked.
String mobileDate= (String) android.text.format.DateFormat.format("yyyy-MM-dd HH:mm:ss", new java.util.Date());
RetrofitClient
public class RetrofitClient {
private static Retrofit retrofit=null;
private static String base_url= null;
public static void setBaseUrl(String string){
base_url = string;
}
public static void deletePreviousInstance(){
retrofit=null;
}
public static Retrofit getRetrofitInstance(){
if(retrofit==null){
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(25, TimeUnit.SECONDS)
.readTimeout(25, TimeUnit.SECONDS)
.writeTimeout(25, TimeUnit.SECONDS)
.build();
retrofit= new Retrofit.Builder()
.baseUrl(base_url)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
you are giving a string as parameter for date format you have to parse the same date format at the server end. you can check out this link https://stackoverflow.com/a/882465/2285117
Related
I want to get to the service in specific URL .... I use retrofit to get it but it give me an error connection to the URL...while the URL is active in chrome.
in the code I write ??? instead to correct one ^__^ (this code is class APIClient)
and to be sure that I work in correct way I was built an api in mocky site with the same json file .... and it is work
so can any one help me please
public static final String BASE_URL = "http://111.222.1.12:0000/???/???/????/";
//database
public static final String BASE_URL2 = "http://www.mocky.io/v2/";
public static Boolean URL=true;
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit==null) {
if(URL)
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
else
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL2)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
return retrofit;
}
Hello you can try using my ApiClient, I'm using rxJava so you need to redesign the APIClient to your need
public class ApiClient {
private static Retrofit retrofit = null;
private static int REQUEST_TIMEOUT = 120;
private static OkHttpClient okHttpClient;
public static Retrofit getClient(Context context) {
if (okHttpClient == null)
initOkHttp(context);
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(API_PATH)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private static void initOkHttp(Context context) {
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
OkHttpClient.Builder httpClient = new OkHttpClient().newBuilder()
.connectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(interceptor);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Request-Type", "Android")
.addHeader("Content-Type", "application/json");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
okHttpClient = httpClient.build();
}
public static void resetApiClient() {
retrofit = null;
okHttpClient = null;
}
}
Hope this reference can help you solve your problems
I am using retrofit library to upload file to server. When file was uploaded it shows error:: timeout. How to increase upload time so that I can upload full file in server.
Here try this: In below code you will pass your custom OKHTTP client with your custom timeout
public class RetrofitClient {
private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
public static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
You also need this dependency:
implementation 'com.squareup.okhttp3:okhttp:3.10.0'// OKHTTP \\ Add this to your gradle file
Add the following class in your project.
public class Api{
static Gson gson = new GsonBuilder()
.setLenient()
.create();
public static Retrofit adapter = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL) //Set the Root URL
.addConverterFactory(GsonConverterFactory.create(gson))
.client(configureTimeouts())
.build(); //Finally building the adapter
public static OkHttpClient configureTimeouts() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(90, TimeUnit.SECONDS) // Set your timeout duration here.
.writeTimeout(90, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS)
.build();
return okHttpClient;
}
}
In the above configureTimeouts() function, you can set the duration after which the timeout occurs according to your requirements.
Also, don't forget to put these dependencies in your app level build.gradle file
compile 'com.squareup.retrofit2:retrofit:2.4.0'
compile 'com.squareup.retrofit2:converter-gson:2.4.0'
public RestAdapter providesRestAdapter(Gson gson) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
return new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_URL)
.setConverter(new GsonConverter(gson))
.setClient(new OkClient(okHttpClient))
.build();
}
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder().readTimeout(120, TimeUnit.SECONDS).connectTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS);
private static Retrofit retrofit;
static {
Builder addConverterFactory = new Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create());
builder = addConverterFactory;
retrofit = addConverterFactory.build();
}
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}
public static <S> S createService(Class<S> serviceClass, String username, String password) {
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
return createService(serviceClass, null);
}
return createService(serviceClass, Credentials.basic(username, password));
}
public static <S> S createService(Class<S> serviceClass, String authToken) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken);
if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
This is my url http://192.168.1.217:8088/api/frontend/web/index.php?r=api/sms/send,and I need take some params,the following is param
{"body":{"param":"VjvBNGoYQ3/nCytxN0zx5rr+6sewp7FABok5N3DdDdD0WWu7KCCohA=="},
"header":{"deviceId":"","appToken":"","serviceCode":"sms","appType":1,"appVersion":1,"clientType":1}}
I shoud how write the code use retrofit?Thanks advanced.
This is the best example I have found on how to use retrofit so far http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
But if you want to another example here is the code i used for OpenWeatherMap.
public class ApiClient {
private static final int TIME_OUT = 30;
public static final String BASE_URL = "http://api.openweathermap.org/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
okBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
okBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
okBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
Gson gson = new GsonBuilder().create();
return new Retrofit.Builder()
.baseUrl(BASE_URL) .addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okBuilder.build())
.build();
}
return retrofit;
}
public interface ApiInterface {
#GET("data/2.5/forecast?id=524901")
Call<WeatherResponse> getWeatherData(#Query("APPID") String apiKey);
}
I have used Retrofit library for my Android application.I need to set connection timeout as 120 Sec. How can I do ?
Version:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
OperatingApiClient:
public class OperatingApiClient {
public static final String BASE_URL = "http://172.16.2.39/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
TargetFileApiInterface:
public interface TargetFileApiInterface {
#GET("NNGOperating/GetTargetFileList")
Call<TargetFileApiResponse> getTargetFileList(#Query("api_key")
String apiKey);
}
TargetFileApiResponse:
public class TargetFileApiResponse {
#SerializedName("TargetFileList")
private List<TargetFile> targetfileslist;
public TargetFileApiResponse(List<TargetFile> targetfileslist) {
this.targetfileslist = targetfileslist;
}
public List<TargetFile> getTargetfileslist() {
return targetfileslist;
}
public void setTargetfileslist(List<TargetFile> targetfileslist) {
this.targetfileslist = targetfileslist;
}
}
You can set configuration for OkHttp
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(yourTime, TimeUnit.SECONDS)
.writeTimeout(yourTime, TimeUnit.SECONDS)
.readTimeout(yourTime, TimeUnit.SECONDS)
.build();
after that, set client for retrofit
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
It is working.
public class OperatingApiClient {
public static final String BASE_URL = "http://172.16.2.39/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(120, TimeUnit.SECONDS)
.connectTimeout(120, TimeUnit.SECONDS)
.build();
}
Try the following, set httpClient for your retrofit builder.
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS); // I am using 60 seconds you can user your own
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build()) //setting your custom client
.build();
}
return retrofit;
}
I have been trying to implement the Bill Pugh Singleton Design Pattern using a private static class to return the singleton retrofit instance. SO far I have been able to come up with the following code. Can someone help me review this code and confirm if this is a proper implementation of the singleton design pattern suggested by Mr. Bill Pugh Himself or suggest me a proper way of implementing this.
public class SingletonRetrofit {
private SingletonRetrofit(){}
private static class SingletonRetrofitHelper {
private static OkHttpClient okHttpClient;
private static Retrofit retrofit;
private static Retrofit makeRetrofit() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.readTimeout(20, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://ci.draftserver.com/hornsbyapp/webservice/")
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
public static Retrofit getInstance() {
return SingletonRetrofitHelper.makeRetrofit();
}
}
USE this one:
public class Apiclient {
private static final String BASE_URL ="URL";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
OkHttpClient.Builder httpClient2 = new OkHttpClient.Builder();
httpClient2.addNetworkInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("site_id","1");
return chain.proceed(builder.build());
}
});
OkHttpClient client = httpClient2.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}