Reputation: 187
When the request is sent through Postman I can see it is sending all Set-Cookie in response header. Example :
Set-Cookie : wfwaf-authcookie-b52dd4381520%...... expires=Fri, 04-Dec-2020 23:32:21 GMT; Max-Age=43200; path=/; secure; HttpOnly
Set-Cookie : woocommerce_items_in_cart=1; path=/
Set-Cookie : woocommerce_cart_hash=92e2c.......; path=/
Set-Cookie : wp_cocart_session_a9339f....; expires=Fri, 11-Dec-2020 11:32:21 GMT; Max-Age=604800; path=/; secure; HttpOnly
But in Retrofit I'm only getting 2 of them. Not all 4. The request url is : https://mywpwebsite.com/wp-json/wc/store/cart
my code for calling retrofit request:
public MutableLiveData<Resource<Cart> > getCartItems(HashMap<String,String> attribs, HashMap<String,String> headers) {
Log.d(TAG, "get cart items: being called");
final MutableLiveData cartitems = new MutableLiveData<>();
WCService service = getRetrofitInstance().create(WCService.class);
Call<Cart> call = service.getCartItems(attribs,headers);
call.enqueue(new Callback<Cart>() {
@Override
public void onResponse(Call<Cart> call, Response<Cart> response) {
Log.d(TAG,"fetched cartitems");
Log.d(TAG,"responsecode:"+response.code());
Log.d(TAG, "onResponse: headers: "+response.headers().toString());
Log.d(TAG, "onResponse: cookie : " + response.headers().toMultimap() .get("Set-Cookie").toString());
if (response.code() == 200) {
if (response.body() != null)
cartitems.setValue(WCRepository.Resource.success(response.body()));
else
cartitems.setValue(WCRepository.Resource.error("Something went wrong, please refresh", null));
} else {
try {
errorResponse er = new Gson().fromJson(response.errorBody().string(), errorResponse.class);
cartitems.setValue(WCRepository.Resource.error(er.getMessage(), er.getMessage()));
} catch (Exception e) {
cartitems.setValue(WCRepository.Resource.error("error: "+ e.getMessage(), null));
}
}
}
@Override
public void onFailure(Call<Cart> call, Throwable t) {
cartitems.setValue(null);
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
return cartitems;
}
and
@GET("store/cart?")
Call<Cart> getCartItems(@QueryMap() Map<String,String> params, @HeaderMap() Map<String,String> headers);
Upvotes: 2
Views: 1398
Reputation: 187
After trying everything I found on the internet, finally I noticed the Authorization Bearer token is not being sent because I wrote "Authentication" as header name instead of "Authorization" . I have corrected that and it's working perfectly now. But anyone who wants to mess around with headers or cookies , here are few ways :
Cookiejar example :
final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
CookieJar cookiejar = new CookieJar() {
@Override
public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
Log.d(TAG, "saveFromResponse: "+ cookie.name() +":"+ cookie.value());
cookieStore.put(httpUrl.host(), list);
}
@NotNull
@Override
public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
List<Cookie> cookies = cookieStore.get(httpUrl.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
};
OkHttpClient client ;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(cookiejar);
client = builder.build();
HttpLoggingInterceptor example:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(@NotNull String s) {
Log.d("logevent", s); // this will run in loop until finishes reading all headers
}
}).setLevel(HttpLoggingInterceptor.Level.HEADERS);
OkHttpClient client ;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(logging);
client = builder.build();
For reading headers , ReceivedCookiesInterceptor example:
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Response;
public class ReceivedCookiesInterceptor implements Interceptor {
private Context context;
public ReceivedCookiesInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
//cookie headers only
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
for (String header : originalResponse.headers("Set-Cookie")) {
Log.d(TAG, "cookie: "+header);
}
}
//for any other headers
Map m = originalResponse.headers().toMultimap();
Iterator it = m.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
Log.d(TAG, "intercept: "+pair.getKey() + " = " + pair.getValue());
it.remove();
}
return originalResponse;
}
}
for manipulating headers, AddCookiesInterceptor :
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.util.HashSet;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class AddCookiesInterceptor implements Interceptor {
public AddCookiesInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
//for adding headers:
builder.addHeader("key", "value");
//for replacing headers:
builder.header("key", "value");
return chain.proceed(builder.build());
}
}
then just as before add these as interceptors. You might need to add these to your dependency :
implementation("com.squareup.okhttp3:logging-interceptor:4.9.0")
implementation "com.squareup.okhttp3:okhttp-urlconnection:3.6.0"
Upvotes: 1