recvfrom failed: ECONNRESET (Connection reset by peer) - android

I am trying to Delete some medias from my mobile application using retrofit2 REST client.
#HTTP(method = "DELETE",path="/api/v1/media/{username}/{accesstoken}", hasBody = true)
Call<MyResponse> deleteArchiveMedia(#Path("username") String username, #Path("accesstoken") String token ,
#Body DeleteMedia deleteMedia);
This is the call for delete.
DeleteMedia is a class which contains 2 array lists, one is for channelId and other for Mediaid's
Delete is working when delete a few medias (less than 100),but while delete more than 100 medias it will return an error like:
recvfrom failed: ECONNRESET (Connection reset by peer)
Why this is happening only when I am trying to delete large amount of size medias?
Is there any limit for retroffit2 body length?
Please help me......
class for getting retrofit
public class DeleteModule {
private static Retrofit retrofit = null;
public static Retrofit getClient() {
System.setProperty("http.keepAlive", "false");
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60,TimeUnit.SECONDS)
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(Constants.getBaseURL())
.addConverterFactory(GsonConverterFactory.create()).client(okHttpClient)
.build();
}
return retrofit;
}
}

Related

Android okhttp3 socket connection problem

Can't connect to socket server with error: java.net.ProtocolException: Expected HTTP 101 response but was '404 Not Found'.
Code:
`
private fun run() {
val client: OkHttpClient = OkHttpClient.Builder()
.readTimeout(3, TimeUnit.SECONDS)
.build()
val request: Request = Request.Builder()
.url(AppParams.SOCKET)
.build()
client.newWebSocket(request, this)
client.dispatcher.executorService.shutdown()
}
`
Url format is: "https://url.com:3003/".
The SocketIO library works correctly
Tried to remove the prefix, change the port, use another link..
You should change the link to "wss://url.com:3003/"

WebServices not working with retrofit but working properly in Postman

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

Retrofit with OkHTTP not set Content-Type with #FormUrlEncoded

I'm trying to implement auth via x-www-form-urlencoded with Retrofit 2 on Android but faced a problem, that Header Content-Type not set with #FormUrlEncoded annotation, as well as I'm trying to set it manually, but when I'm setting it with a typo like Cotent-Type it works correctly and I can see it in headers.
Retrofit version: 2.4.0
So my question: why #FormUrlEncoded not set a content type as well as #Header annotation or what can remove it from headers.
My request:
#FormUrlEncoded
#POST("account/login")
Single<LoginResponse> login(#Field("memberId") String memberId,
#Field("pin") String pin);
OkHTTP/Retrofit provider with interceptors:
#Singleton
#Provides
Retrofit provideRetrofit(final OkHttpClient client, final Moshi moshi) {
return new Retrofit.Builder()
.baseUrl(Configuration.BASE_URL)
.client(client)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
#Provides
OkHttpClient provideOkHttpClient(#AppContext final Context context) {
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.addInterceptor(createLanguageInterceptor(context));
if (BuildConfig.DEBUG) {
builder.addInterceptor(new LoggingInterceptor());
}
return builder.build();
}
Interceptor createLanguageInterceptor(#AppContext final Context context) {
Locale current = context.getResources().getConfiguration().locale;
return chain -> {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("Accept-Language", current.getLanguage());
Request request = builder.build();
Response response = chain.proceed(request);
return response;
};
}
As a workaround, I've implemented the following interceptor:
Interceptor createHeaderTransformationInterceptor() {
return chain -> {
final Request request = chain.request();
String dataType = request.header("Data-Type");
final Request resultRequest = dataType == null
? request
: chain.request().newBuilder()
.removeHeader("Data-Type")
.addHeader("Content-Type", dataType)
.build();
return chain.proceed(resultRequest);
};
}
and it works fine with the following annotation:
#Headers({"Data-Type: application/x-www-form-urlencoded"})
UPD: the reason that my interceptor didn't see that is in a place where the content type is stored. The right way to see that header in an interceptor:
if (requestBody.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
By this Request
#FormUrlEncoded
#POST("account/login")
Single<LoginResponse> login(#Field("memberId") String memberId,
#Field("pin") String pin);
method #POST and #FormUrlEncoded automatic add
Content-Type: application/x-www-form-urlencoded in header you can check in log by
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor.setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(2, TimeUnit.MINUTES)
.writeTimeout(2, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.build();
it print all log in verbose mode

Retrofit socket timeout exception while uploading larger files using multipart

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")

Retrofit response Cache

There are a lot of complex answers here about Retrofit cache but none seem to help me.
How do I cache my code response coming from the Retrofit response?
My App works fine downloading the JSON below but I need to make a cache for it and I never did cache on Android.
I need to open the App offline and get the result from my Retrofit call as if I was online.
public class APIClient {
public static final String BASE_URL = "https://raw.githubusercontent.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}}
The json response is VERY simple:
{
"fruits":[
{
"name":"Apple",
"image":"https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/265px-Red_Apple.jpg",
"price":35
},
{
"name":"Banana",
"image":"https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Bananas_white_background_DS.jpg/320px-Bananas_white_background_DS.jpg",
"price":12
},
{
"name":"Grapes",
"image":"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Table_grapes_on_white.jpg/320px-Table_grapes_on_white.jpg",
"price":45
},
{
"name":"Pineapple",
"image":"https://upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Pineapple_and_cross_section.jpg/286px-Pineapple_and_cross_section.jpg",
"price":200
},
{
"name":"cherry",
"image":"http://www.desicomments.com/wp-content/uploads/2017/05/Cherry-Image-600x570.jpg",
"price":13
},
{
"name":"clementine",
"image":"http://www.icecreamnation.org/wp-content/uploads/2013/04/Clementine_orange.jpg",
"price":12.4
},
{
"name":"olive",
"image":"https://www.homenaturalcures.com/wp-content/uploads/olive.jpg",
"price":9.5
},
{
"name":"tomato",
"image":"http://cdn2.stylecraze.com/wp-content/uploads/2013/05/tomato-hair-benefits1.jpg",
"price":8.75
},
{
"name":"huckleberry",
"image":"http://farm3.static.flickr.com/2131/2082287810_47339fc93e.jpg",
"price":11.75
},
{
"name":"papaya",
"image":"http://media.mercola.com/assets/images/foodfacts/papaya-nutrition-facts.jpg",
"price":2.75
},
{
"name":"lime",
"image":"https://www.florihana.com/images/stories/virtuemart/product/FLE019%20-%20LIME.jpg",
"price":5.75
},
{
"name":"pear",
"image":"https://www.organicfacts.net/wp-content/uploads/pear.jpg",
"price":4.75
}
]
}
Assuming server respects Cache-Control/If-Modified-Since headers, than all you have to do is to create a Cache object and set it to OkHttpClient. Retrofit will take care of the rest.
int cacheSize = 10 * 1024 * 1024; // 10 MB
Cache cache = new Cache(getCacheDir(), cacheSize);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(cache)
.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:3000/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Source: futurestud.io
Inorder cache our server response using retrofit 2.0 and okHttp, we all need is OkHttpClient, AddNetworkInterceptor add cache interceptor, you can not use. AddInterceptor, also need not both at the same time.
This method requires no server-side operation, no other server-side caching strategy, if the server has its own cache strategy code should be modified accordingly to adapt to the server.
You can refer this link , it helped me to solve my problem

Categories

Resources