简体   繁体   中英

how to get session cookie from server and set it into the api header?

There is cookie header in my api request, every time I have to copy this cookie from postman and paste in my code to make it work. how can I generate cookie in my app and give that value in cookie header?

this is my login code:

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("username","zee@earthonetechno.com")
  .addFormDataPart("password","E1234567")
  .build();
Request request = new Request.Builder()
  .url("192.168.1.51/auth/login")
  .method("POST", body)
  .addHeader("User-Agent", "Koala Admin")
  .addHeader("Content-Type", "application/json")
  .addHeader("Cookie", "session=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")
  .build();
Response response = client.newCall(request).execute();

I want to put the cookie here in addHeader("Cookie", "session=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")

I am developing in android studio

I found the solution for this

just include these lines in login part to get cookie

Headers allHeaders = response.headers();
headerValue = allHeaders.get("Set-Cookie");

and use this headerValue for subsequent api calls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM