FAQ Database Discussion Community


Download progress with RxJava, OkHttp and Okio in Android

android,rx-java,okhttp,okio
In our app I download an image file with this code. I need to show download progress(downloaded bytes in percentage) on UI. How I can get download progress in this code? I searched for solution, but still can't manage to do it on my own. Observable<String> downloadObservable = Observable.create( sub...

Multipart file upload with OkHttp + Spring

android,spring,spring-mvc,okhttp
I recently switched to OkHttp. After the switch, the code below does the upload. RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addPart( Headers.of("Content-Disposition", "form-data; name=\"qqfile\""), RequestBody.create( MediaType.parse(filename), new File(filename))) .build(); If you compare images, the second image has multipartFiles size = 0. It should be of size = 1. How to...

Does anyone know when Cordova for Android will be updated & built against okhttp v2.x?

android,cordova,okhttp
I have other libraries in my app that use okhttp 2.x, and I can't build against them both as I get runtime exceptions. Sadly okhttp didn't leave the deprecated methods in their SDK when they moved to v2.x :-( Given okhttp 2.x was released in may 2014, I'm hoping Cordova...

How to alert the user using Toast that the OkHttp request returned something other than 200?

android,okhttp,android-toast
I'm using OkHttp and everything is working fine, however, I wanted to take into consideration the case where the DNS resolution is off, the server is down, slow, or simply returns something other than HTTP Status Code 200. I've tried to use Toast, but I can't since this is done...

Intercept and retry call by means of OkHttp Interceptors

interceptor,retrofit,okhttp
I need to retry request inside of OkHttp Interceptor. For example there is incoming request which needs Authorization token. If Authorization token is expired, server returns response with 403 code. In this case I am retrieving a new token and trying to make call again by using the same chain...

How to read the status code of Okhttp response in android

android,okhttp
My Current code: public static InputStream postRequestWithPayload(String url, String mJsonReq) throws Exception { Response response; try{ RequestBody body = RequestBody.create(JSON, mJsonReq); client.setConnectTimeout(20, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(20, TimeUnit.SECONDS); // socket timeout Request request = new Request.Builder() .url(url) .post(body) .addHeader(AppConstants.OKHTTP_HEADER_GENERAL_USERNAME, AppController.getUserName()) .addHeader(AppConstants.OKHTTP_HEADER_GENERAL_AUTHTOLKEN,...

Consuming One-Shot ResponseBody from Okhttp causes issues with Retrofit

java,android,retrofit,okhttp
I am using an Retrofit with an Okhttp interceptor in order to detect if my oauth token has expired. If the token has expired, I want to request a new token, try the request again, then send that response to Retrofit. Here is my interceptor class: public class CustomInterceptor implements...

OkHttp, is the automatic GZIP disabled when using a custom interceptor?

android,gzip,okhttp
I am using OkHttp 2.3.0 in my Android app. My question is about the transparent GZIP feature. According to the documentation, it should be silently there. But I cannot see the ("accept-encoding", "gzip") header in the request. I am using a custom interceptor to add authentication: @Override public Response intercept(Chain...

HttpURLConnection failes with NullPointerException on Lollipop

android-5.0-lollipop,universal-image-loader,okhttp
I noticed that sometimes, not sure in which conditions, while downloading an image using Universal-Image-Loader (https://github.com/nostra13/Android-Universal-Image-Loader), I get the following NullPointerException: E/ImageLoader(27386): Attempt to invoke virtual method 'boolean java.lang.String.startsWith(java.lang.String)' on a null object reference E/ImageLoader(27386): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.startsWith(java.lang.String)' on a null object reference E/ImageLoader(27386): at...

okhttp application level OkHttpClient instance

java,okhttp
I was wondering if there will be any performance bottleneck or issues if I create one instance of OkHttpClient to serve my "entire android application". I.e.In my Application class, I create a static public variable that will contain a instance of OkHttpClient and whenever I need to do an http...

SPDY multiplexing makes requests slower than HTTP

android,performance,okhttp,spdy,multiplexing
I have an application that makes a mixture of network requests, some small items (~20kB) and some large items (>2mB). If my understanding of SPDY is correct, SPDY multiplexes requests on the same connection, so the smaller requests could potentially be slowed down if they're behind the larger requests. Since...

Retrofit + OkHTTP - response cache not working

android,caching,retrofit,cache-control,okhttp
I know there has been a lot of similar questions, but I have read them all and none of them really helped. So, here is my problem: I am using retrofit + okhttp to fetch some data from API and I'd like to cache them. Unfortunately, I don't have admin...

How to convert the response from Okhttp into inputstream

android,inputstream,okhttp
CODE: public static String getRequestNoPayload(String urlString, String loginApi, String mUsername) throws Exception { Response response; try{ client.setConnectTimeout(20, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(20, TimeUnit.SECONDS); // socket timeout Request request = new Request.Builder() .url(urlString) .addHeader("username",loginApi) .addHeader("password",mUsername) .build(); response = client.newCall(request).execute(); }catch(Exception e){ throw e; } return response.body().string(); } What i am trying...

java.lang.VerifyError when using OkHttp

android,okhttp,okio
I use this code in my android studio project: HttpUrl url = new HttpUrl.Builder().scheme("http").host("www.somesite.com") .addPathSegment("kontakt") .addQueryParameter("yit_contact[imie]", name) .addQueryParameter("yit_contact[email]", email) .addQueryParameter("yit_contact[telefon]", telephone) .addQueryParameter("yit_contact[wiadomosc]", message) .addQueryParameter("yit_bot", "") .addQueryParameter("_wp_http_referer", "/kontakt/").build(); Request request = new Request.Builder().url(url).build(); Response response = new...

Can't get OkHttp's response.body.toString() to return a string

java,android,okhttp
I'm trying to get some json data using OkHttp and can't figure out why when i try logging the response.body().toString() what i get is Results:﹕ [email protected] try { URL url = new URL(BaseUrl); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header(/****/) .build(); Call call = client.newCall(request);...

get push stream in response send by server push with OkHttp

android,push,okhttp,http2
I am trying to test the push response from a server which support HTTP2 Server with an android app (Os=Android KitKat) . The server push another ressources(pictures) after a http request for index.html. I don't know how to access to push stream (picture). I have done capture on server and...

Robospice service running until it finish it job after application finished

okhttp,robospice
I have an application that access to a server. When I quit the application, I have to disconnect from the server first, then close the application. I would like to know if it's possible (and how) to make a Robospice service (background task) that disconnect from the server even if...

CookieManager is abstract, cannot be instantiated. Why?

android,okhttp,android-cookiemanager
OkHttpClient client = new OkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); throws "CookieManager is abstract, cannot be instantiated" I'm importing android.webkit.CookieManager and everything seems fine from the documentation side. ...

Best way to download a file in an Android app

android,download,android-download-manager,okhttp
I try to understand the pros and cons of different ways to download a file using an android app. I found several ways: Managing the download on my own (see this code snippet) Using Android's DownloadManager Downloading a file using OKHttp as described in this post Does anyone with experience...

RxJava, OkHttp, Okio, file downloader in Android

android,rx-java,okhttp
I am trying to convert this working file download code to Reactive. But got stuck, due to my little knowledge of RxJava. Could you help me to make it Reactive? public void downloadFile(MessageComponent media) { Request request = new Request.Builder() .url(media.getMediaUrl()) .build(); Call call = http_client.newCall(request); call.enqueue(new Callback() { @Override...

Android unable to parse json from api.openweathermap.org

android,json,parsing,http,okhttp
I'm parsing json from this link "api.openweathermap.org/data/2.5/forecast/daily?q=51310&mode=json&units=metric&cnt=7" First i did json parsing using urlhttpconnection and its work then i add progressbar and try again to parse and got nothing. I also tried okhttp but not work then i changed my url then its work perfectly whats the reason? If i...

Are Retrofit and OkHttp suitable for Java EE/Server-side use?

rest,java-ee,server-side,retrofit,okhttp
I like the APIs of the Retrofit and OkHttp rest/http libraries from Square. I am evaluating options for writing a server-side rest client. For each request to my SOAP-based web service, I have to consume another, restful web service, thus my need for a rest client. My question is, are...

How does OkHttp get Json string?

http,embedded-jetty,okhttp
Im using Jetty servlet, the URL ishttp://172.16.10.126:8789/test/path/jsonpage, every time request this URL it will return {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} It shows up when type the url into a browser, unfortunately it shows kind of memory address other than the json string when I request with Okhttp....

OkHttp how to log request body

android,okhttp
I'm using an interceptor, and I would like to log the body of a request I'm making but I can't see any way of doing this. Is it possible ? public class LoggingInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1...

Image adapter leaking memory

android,recyclerview,listadapter,picasso,okhttp
I have a simple ListActivity that shows images and I inizialize my OkHttpClient for Picasso Builder in the constructor of the ImageAdapter class: picassoClient = new OkHttpClient(); picassoClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request newRequest = chain .request() .newBuilder() .addHeader("Cookie","xyz") .build(); return chain.proceed(newRequest); } });...

How cancel task with retrofit and rxjava

retrofit,reactive-programming,rx-java,okhttp
I have rest api. @Get("/serveraction") public Observable<String> myRequest(@Query("Data") String data); I know, that okhttp has canceling functionality(by request object, by tag), but don't know how use it with retrofit and rxjava. What is the best way to realize canceling mechanism for network tasks with retrofit and rxjava?...

Gradle - Error:Failed to find: com.squareup.okhttp:okhttp:2.4.0

android,android-studio,gradle,okhttp
I just try to use OkHttp but I have the following issue when I sync my gradle file with Android Studio : Error:Failed to find: com.squareup.okhttp:okhttp:2.4.0 Here is the dependencies part of my build.gradle file : dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:22.1.1' compile 'com.google.android.gms:play-services-maps:6.5.87' compile 'com.squareup.okhttp:okhttp:2.4.0' }...

How to add query parameters to a HTTP GET request by OkHttp?

java,http-get,okhttp,query-parameters
I am using the latest okhttp version: okhttp-2.3.0.jar How to add query parameters to GET request in okhttp in java ? I found a related question about android, but no answer here!...

Crashlytics Initialization ConnectionException (EHOSTUNREACH)

android,crashlytics,okhttp,fabric-twitter,httpexception
I have the Crashlytics SDK installed on an Android app (through Fabric) and it was working perfectly before. All of a sudden, I'm getting ConnectionExceptions and Crashlytics cannot communicate with its remote server. Fabric is instantiated at the end of onCreate in my Application class: public void onCreate() { super.onCreate();...

okhttp-urlconnection test crashes mockwebserver, yet passes

okhttp
Run 'mvn install' on okhttp, okhttp-urlconnection, and mockwebserver, then run 'mvn test' in okhttp-urlconnection: Mar 08, 2015 11:53:54 AM com.squareup.okhttp.mockwebserver.MockWebServer$3 execute SEVERE: MockWebServer[51929] connection from /127.0.0.1 crashed java.lang.IllegalStateException: closed at okio.RealBufferedSource.indexOf(RealBufferedSource.java:293) at okio.RealBufferedSource.indexOf(RealBufferedSource.java:289) at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196) at...

PATCH Verb in Android (OkHttp, Volley, Retrofit…)

android,android-volley,okhttp
I know a similar question has been asked a few times now, but I can't seem to find a solution for a simple problem: PATCH verb. So I ask anyone who as solved the PATCH issue in Android either by using OkHttp, Volley or Retrofit ( or if you used...

OkHttpClient close connection

java,android,okhttp
I'd like to use OkHttpClient to load a url, and if the website at the given url responds with a pdf content type I will go ahead and download the PDF, otherwise I want to ignore the response. My question is, do I need to do anything special to close...

OKHTTP — Posting user-input data, retrieving JSON response to determine success

java,php,json,http,okhttp
I've been thinking in how to do this. I've read trough the OKHTTP documentation, I have an idea on how to handle this but I'm not entirely sure. I'll have the user submit three fields ( Username, Password, Database ). I'll have a PHP file uploaded to my host which...

How to configure the Http Cache when using Volley with OkHttp?

android,android-volley,okhttp
In my project, i want to try Volley combining with OkHttp. But the cache system of Volley and OkHttp both rely on the HTTP cache as defined in the HTTP specification. So how to disable the cache of OkHttp for keeping one copy of HTTP cache? EDIT: what i have...

OkHttp Caching Policies and ETags

okhttp
I had some questions about OkHttp and how it chooses to do caching: Does OkHttp honor Weak ETag (which is used by default in Tomcat 7)? I read somewhere that Chrome ignores any Weak ETags in favor of the Last-Modified response header. I'm not certain if this is true for...

Android, get data from web and update UI (Multi-threading and MVC design pattern)

java,android,multithreading,okhttp
Currently developing a weather application . I wanna strictly observe 2 rules: MVC Design pattern Multithreading when I deals with network. The problem is combining these things into a whole, here are parts of my code: Weather Class (represent a Weather object) : public class Weather { private int mTimeInSeconds;...

Retrofit and OkHttpClient, catch connection timeout in failure method

android,retrofit,connection-timeout,okhttp
I have the following setup: final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setReadTimeout(5, TimeUnit.SECONDS); okHttpClient.setConnectTimeout(5, TimeUnit.SECONDS); RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(ROOT) .setClient(new OkClient(okHttpClient)) .setLogLevel(RestAdapter.LogLevel.FULL); I am trying to handle the situation in which my server is down and the user gets a connection timeout exception, this is my logging: java.net.SocketTimeoutException:...

Now that SSLSocketFactory is deprecated on Android, what would be the best way to handle Client Certificate Authentication?

android,ssl,okhttp,pkcs#12
I am working on an Android app that requires Client Certificate Authentication (with PKCS 12 files). Following the deprecation of all that's apache.http.*, we have started a pretty big work of refactoring on our network layer, and we have decided to go with OkHttp as a replacement, and so far...

How to use network frameworks (volley , okhttp , etc) in libgdx?

android,libgdx,android-volley,okhttp
I want to load some data from web using volley or okhttp in libgdx. How to use network frameworks like volley or okhttp in libgdx instead of libgdx networking class ?...

Retrieving JSON data asynchronously

android,json,asynchronous,okhttp
So, maybe someone with a little more experience with Square's OkHttp library for Android will be able to explain to me exactly what is going on. I understand the concept of the UI thread and asynchronous requests to the web, as to not clutter up the UI thread. My question...

How to handle auth0 403 error without adding specific code everywhere (Retrofit/okhttp/RxAndroid)

android,retrofit,rx-java,okhttp,auth0
I am using Auth0, which gives me a JWT (json web token) and a refreshtoken. I use this JWT in the http headers to communicate with my backend. It could happen, that the server gives me a 403, when it decides that the JWT has expired. In this event, I...

Is there a way to feed a cached response to Retrofit?

android,sqlite,retrofit,okhttp
For various reasons (one of which being that I have no control on the REST server) I cannot use the standard HTTP cache with OkHTTP. The idea would be to use Retrofit to work with the services and store the responses in a local cache (SQLite). The problem then is...