when does okhttp client cache the server response? - java

I am using okhttp client 3.5.0 in java to cache the response and server response has below cache-control header:
Cache-Control: private, max-age=0, must-revalidate
First I am trying to make actual network call to get the server response, then in second request I want to get cached response.
Here is my java code:
HttpUrl.Builder httpUrlBuilder = HttpUrl.parse(serverUrl).newBuilder();
HttpUrl httpUrl = httpUrlBuilder.build();
Request request = new Request.Builder()
.url(httpUrl)
.cacheControl(new CacheControl.Builder().maxAge(1, TimeUnit.DAYS).build())
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
System.out.println("***************Response 1**************");
System.out.println("isSucess:"+response.isSuccessful());
Response text = response.cacheResponse();
System.out.println("Cached Response:" + text);
Response networkResponse = response.networkResponse();
System.out.println("Network Response ::" +networkResponse);
}
});
Thread.sleep(5000);
Request request2 = new Request.Builder()
.cacheControl(new CacheControl.Builder().onlyIfCached().build())
.url(httpUrlBuilder.build())
.build();
call = okHttpClient.newCall(request2);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
System.out.println("***********Response 2************");
System.out.println("isSucess:" +response.isSuccessful());
final Response text = response.cacheResponse();
System.out.println("Cached Response:" + text);
Response networkResponse = response.networkResponse();
System.out.println("Network Response:" +networkResponse);
}
});
And below is the second request output:(partial output)
***********Response 2************
isSucess:false
Cached Response:null
Network Response:null
Whether I am missing anything?

OkHttp won’t cache a response unless you read and close the response body. This is what triggers those bytes to be downloaded and saved.
try {
if (response.cacheResponse() == null) {
body.source().skip(Long.MAX_VALUE); // Exhaust response body.
}
} finally {
body.close();
}

Related

Android HTTP Get to api

I´m trying to get data from my api. In postman the request works, here´s the response:
{
"ips_Beacons_BeaconID": 14,
"ips_Beacons_BeaconDescription": "b2",
"ips_Beacons_BeaconLat": 12.3123,
"ips_Beacons_BeaconLon": 32.123,
"ips_Beacons_BeaconImgX": 45,
"ips_Beacons_BeaconImgY": 123
}
I´ve tried and i got the response with Okhttp. However it stopped working for some reason.
Although i got the response, i wish to serialize the json string it and instanciate objects. But i couldn´t get the response out of the onSuccess method inside the callback.
This is what i had that workd but doens´t work anymore:
OkHttpClient client = new OkHttpClient();
String url ="http://192.168.1.95:44374/api/beacons";
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) { e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String myResponse = response.body().string();
listBeacons = objectMapper.readValue(myResponse, new TypeReference<List<Beacon>>(){});
Log.i(TAG, myResponse);
}
}
});
I need the listBeacons List to perform other operations outside this activity.

Uploading image on imgur results OK, but no data

I'm trying to upload images from my android apk.
I use this code, seems works, but I getting no data response
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("image", getBase64Image(bitmapImage))
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("https://api.imgur.com/3/image")
.method("POST", body)
.addHeader("Authorization", "Client-ID " + CLIENT_ID)
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.d("ERROR",e.getMessage());
}
#Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
//My code
}
});

GET Request returning 403 Forbidden but works on apitester?

I am trying to get the responce from the server but it is returinig 403 forbidden but testing api on apitester.com works.
This is the code how i am reqesting the get method :
public void getResponse(Context context) throws IOException {
OkHttpClient client = new OkHttpClient();
Hmac hmac = new Hmac();
String auth = hmac.txt;
String url = "https://api.hotstar.com/h/v1/play?contentId=1000034502";
Request request = new Request.Builder()
.url(url)
.addHeader("hotstarauth",auth)
.addHeader("referer","https://hotstar.com/movies/2-states/1000034502")
.addHeader("x-country-code","IN")
.addHeader("x-platform-code","TABLET")
.addHeader("x-region-code","undefined")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("Server Responded: ", response.toString());
}
});
}
and in response i am getting 403 FORBIDDEN
but using the same config on apitester.com it works !
here is the sharedconig on apitester https://www.apitester.com/shared/checks/dca814bb92fb40af8aecda95cdf2f39c
why i am not getting the response on android ?

500, Internal Server Error in Retrofit 2

I have 500 internal server error, every time when i try to send POST request via Retrofit. When i sending GET request, it sending correctly. I'm sure that with serverside everyting is ok. What's wrong with my code ?
Here is my request method
#POST("/listing/createListing")
Call<ResponseBody> pushData(#Body RequestBody image);
post implementation modelTask is my model class object and firebaseToken is firebase authentication token. In my model class, I am saving images as a file list.
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new
Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws
IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " +
firebaseToken)
.build();
return chain.proceed(newRequest);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://something.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiEndPoint apiService = retrofit.create(ApiEndPoint.class);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("title", modelTask.getTitle());
builder.addFormDataPart("description", modelTask.getDescription());
builder.addFormDataPart("user_name", "Josim Uddin");
builder.addFormDataPart("user_id", "2133323");
builder.addFormDataPart("price", "30.0");
builder.addFormDataPart("category_name", "Cleaning");
builder.addFormDataPart("category_id", "123");
builder.addFormDataPart("preferred_date",
modelTask.getPreferred_date());
builder.addFormDataPart("preferred_time",
modelTask.getPreferred_time());
builder.addFormDataPart("hasPet", modelTask.getHasPet());
builder.addFormDataPart("budget",
String.valueOf(modelTask.getBudget()));
builder.addFormDataPart("address", modelTask.getAddress());
builder.addFormDataPart("longitude",
String.valueOf(modelTask.getLongitude()));
builder.addFormDataPart("latitude",
String.valueOf(modelTask.getLatitude()));
builder.addFormDataPart("equipment", modelTask.getEquipment());
for (int i = 0; i < modelTask.getImages().size(); i++) {
builder.addFormDataPart("image[]",
modelTask.getImages().get(i).getName(),
RequestBody.create(MediaType.parse("multipart/form-data"),
modelTask.getImages().get(i)));
}
MultipartBody requestBody = builder.build();
Call<ResponseBody> call = apiService.pushData(requestBody);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.d(TAG, "onResponse:" + response.code()+",
"+response.message());
if (response.isSuccessful()) {
try {
Log.d(TAG, "post submitted code:" +
response.code()+"body:"+response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "Unable to submit post to API::
"+t.getMessage());
}
});
Postman test is successful.
Try this
#POST("listing/createListing")
Call<ResponseBody> pushData(#Body RequestBody image);
Remove "/" from the link and add it to the end of Base Url.

Android OkHttp library: GET Request - Exception EOFException: \n not found: size=0 content=

I'm using in my app OkHttp library (http://square.github.io/okhttp/) and in one simple GET request I get this exception:
Caused by: java.io.EOFException: \n not found: size=0 content=...
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:201)
at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
...
unexpected end of stream on Connection{th.it-bedna.cz:80, proxy=DIRECT# hostAddress=85.118.128.42 cipherSuite=none protocol=http/1.1} (recycle count=0)
Other Get requests to the same address works OK. And if I type this request to the Chrome it works also OK. Do you know where is a problem?
Thanks for any advice.
Edit: code of the GET
public Call doGetRequest(String url, Callback callback) {
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
Using:
void getData()
{
String url = "http://th.it-bedna.cz/api/v2/event/1/user?i=8";
Singleton.getInstance().doGetRequest(url, new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.i("CDT", "onFailure: " + e);
}
#Override
public void onResponse(Response response) throws IOException {
}
});
}
If your server is th.it-bedna.cz as in your logcat info, you can try the following code:
OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
.url("http://th.it-bedna.cz")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e(LOG_TAG, e.toString());
}
#Override
public void onResponse(Response response) throws IOException {
Log.w(LOG_TAG, response.body().string());
Log.i(LOG_TAG, response.toString());
}
});
I had the same issue with OkHttpClient and HttpURLConnection.
My android emulator was configured to use proxy, but my proxy wasn't accepting connections.
Doesn't mater if you use proxy or not if destination host refuses connection you will get that exception.

Categories