I am trying to use this following JSON file as input :
{
"partnerID": "529",
"requests": [
{
"agencyId": "461007",
"lobCd": "LM"
},
{
"agencyId": "023000",
"lobCd": "LM"
},
{
"agencyId": "103000",
"lobCd": "GL"
},
{
"agencyId": "023000",
"lobCd": "GL"
}
]
}
These are my 2 POJO files :
#Getter
#Setter
public class Root {
public String partnerID;
public List<Request> requests;
}
#Getter
#Setter
public class Request {
public String agencyId;
public String lobCd;
}
Request Body
public class SuccessfulRequestBody {
public Object getLobSycbBody_Successful() {
Root root = new Root();
Request request = new Request();
List<Request> requests = new ArrayList<Request>();
root.setPartnerID("529");
request.setAgencyId("461007");
request.setLobCd("LM");
requests.add(request);
root.setRequests(requests);
requests = new ArrayList<Request>();
request.setAgencyId("023000");
request.setLobCd("LM");
requests.add(request);
root.setRequests(requests);
requests = new ArrayList<Request>();
request.setAgencyId("103000");
request.setLobCd("GL");
requests.add(request);
root.setRequests(requests);
requests = new ArrayList<Request>();
request.setAgencyId("103000");
request.setLobCd("GL");
requests.add(request);
root.setRequests(requests);
requests = new ArrayList<Request>();
request.setAgencyId("023000");
request.setLobCd("GL");
requests.add(request);
root.setRequests(requests);
return root;
}
}
Problem : When I run the test I only get the last agency 023000, the others are not getting added to the list. I wanted to see all the other agencies, lob in my output file.
#Test
public void getSuccessResponse(){
String token= generateToken.getGenerateToken();
SuccessfulRequestBody successfulRequestBody = new SuccessfulRequestBody();
Response response = given().log().all().contentType("application/json; charset=utf-8").
contentType("application/json; charset=utf-8").
header("Content-Type", "application/json").
header("Authorization", "Bearer "+token).
//baseUri("https://test-cerebria.test.homesitecommercial.kitchen/api/msaivanspolicyservice/agent/lobSync").
body(successfulRequestBody.getLobSycbBody_Successful()).
when().
post("https://test-cerebria.test.homesitecommercial.kitchen/api/msaivanspolicyservice/agent/lobSync").
then().
extract().response();
}
}
Output :
{
"partnerID": "529",
"requests": [
{
"agencyId": "023000",
"lobCd": "GL"
}
]
}
Thanks in advance for your time and ideas.
The right approach would be to create multiple objects for the class request, set the values and add them to a list
Root root = new Root();
Request request1 = new Request();
Request request2 = new Request();
Request request3 = new Request();
Request request4 = new Request();
request1.setAgencyId("461007");
request1.setLobCd("LM");
request2.setAgencyId("023000");
request2.setLobCd("LM");
request3.setAgencyId("103000");
request3.setLobCd("GL");
request4.setAgencyId("023000");
request4.setLobCd("GL");
List<Request> list = new LinkedList<Request>();
list.add(request1);
list.add(request2);
list.add(request3);
list.add(request4);
root.setPartnerID("529");
root.setRequests(list);
Related
Is it possible to send a form-url-encoded request with json in payload without actually encoding json ? Payload is of form jData=json.
I have tried various combination of form headers and BodyInserters, but it is not working, some time content header is wrong, other times body itself is totally JSON which again at the server API level is not desirable.
I have tried to overwrite request content in onRequestContent method in comment piece of code, hoping with this interception I would be able to override request, but still body is not changed.
Please help.
public class FinvasiaAuthenticationProvider implements BrokerAuthenticationProvider {
private static Logger LOGGER = LoggerFactory.getLogger(FinvasiaAuthenticationProvider.class);
private final WebClient client;
private final FinvasiaProperties properties;
private final ObjectMapper mapper;
public FinvasiaAuthenticationProvider(FinvasiaProperties properties,
ObjectMapper mapper) {
this.client = this.jettyHttpClient();
this.properties = properties;
this.mapper = mapper;
}
#Override
public Mono<BrokerAuthentication> authenticate(BrokerAuthenticationRequest req) {
if (!(req instanceof FinvasiaAuthenticationRequest)) {
return Mono.error(IllegalArgumentException::new);
}
var endpoint = String.format("%s/%s", properties.baseUrl(), FinvasiaUrls.LOGIN_URL.url());
var payload = new FinvasiaAuthenticationRequestAdapter(((FinvasiaAuthenticationRequest) req));
String json;
try {
json = mapper.writeValueAsString(payload);
} catch (JsonProcessingException e) {
return Mono.error(e);
}
var hello = "Hello";
Map<String, String> map = new HashMap<>();
map.put("jData", json);
return client.post()
.uri(endpoint)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.body(BodyInserters.fromFormData("jData", json))
.retrieve()
.onStatus(HttpStatus::is4xxClientError, clientResponse -> {
clientResponse.bodyToMono(String.class).log().subscribe();
return Mono.error(IllegalArgumentException::new);
})
.bodyToMono(String.class)
.map(response -> {
return new FinvasiaAuthentication("1234", Arrays.asList());
});
}
private Request enhance(Request inboundRequest) {
StringBuilder log = new StringBuilder();
inboundRequest.onRequestBegin(request -> log.append("Request: \n")
.append("URI: ")
.append(request.getURI())
.append("\n")
.append("Method: ")
.append(request.getMethod()));
inboundRequest.onRequestHeaders(request -> {
log.append("\nRequest Headers:\n");
for (HttpField header : request.getHeaders()) {
log.append("\n" + header.getName() + ":" + header.getValue());
}
log.append("\n\n");
});
// inboundRequest.onRequestContent((request, content) -> {
//
//
// String b = StandardCharsets.UTF_8.decode(content).toString();
// String[] parts = StringUtils.split(b, '=');
// String decoded = UriUtils.decode(parts[1], StandardCharsets.UTF_8);
//
// content.clear();
// content.put(String.format("%s=%s", parts[0],decoded ).getBytes(StandardCharsets.UTF_8));
//
// request.content(n)
//
// });
inboundRequest.onRequestContent((request, content) ->
log.append("Body: \n\t")
.append(StandardCharsets.UTF_8.decode(content)));
log.append("\n");
inboundRequest.onResponseBegin(response -> {
log.append("Response:\n")
.append("Status: ")
.append(response.getStatus())
.append("\n");
});
inboundRequest.onResponseHeaders(response -> {
log.append("\nResponse Headers:\n");
for (HttpField header : response.getHeaders()) {
log.append("\n" + header.getName() + ":" + header.getValue());
}
log.append("\n\n");
});
inboundRequest.onResponseContent((respones, content) -> {
var bufferAsString = StandardCharsets.UTF_8.decode(content).toString();
log.append("Response Body:\n" + bufferAsString);
});
LOGGER.info("HTTP -> \n");
inboundRequest.onRequestSuccess(request -> LOGGER.info(log.toString()));
inboundRequest.onResponseSuccess(response -> LOGGER.info(log.toString()));
inboundRequest.onResponseFailure((response, throwable) -> LOGGER.info(log.toString()));
return inboundRequest;
}
public WebClient jettyHttpClient() {
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
HttpClient httpClient = new HttpClient(sslContextFactory) {
#Override
public Request newRequest(URI uri) {
Request request = super.newRequest(uri);
return enhance(request);
}
};
return WebClient.builder().clientConnector(new JettyClientHttpConnector(httpClient))
// .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.build();
}
}
I am trying to implement on a Blazor-Server side application a simple login against LDAP server and use cookie to store user claims. I have the MainLayout set to Authorized, if the user is not authenticated it will be re-direct to Login page. I have already tested the LDAP connection and it works properly, the problem is no matter what I do the cookie doesn't get created in the browser. When I run the POST command I see the HttpStatusCode.OK but the cookie it's not created and the browser re-direct again to login page of course.
Can someone please tell me what am I doing wrong? My code:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
AuthenticationController.cs
[ApiController]
public class AuthenticationController : Controller
{
[HttpPost]
[Route("authentication/login")]
public async Task<ActionResult> Login([FromBody]UserCredentials credentials)
{
string path = "LDAP://serveraddress.xxx";
try
{
using DirectoryEntry entry = new(path, credentials.Username, credentials.Password);
using DirectorySearcher searcher = new(entry);
searcher.Filter = $"(&(objectclass=user)(objectcategory=person)(samaccountname={credentials.Username}))";
var result = searcher.FindOne();
if (result != null)
{
List<Claim> claims = new();
claims.Add(new Claim(ClaimTypes.Name, credentials.Username));
//Get Groups
ResultPropertyCollection fields = result.Properties;
foreach (var group in result.Properties["memberof"])
{
var distinguishedName = new X500DistinguishedName(group.ToString());
var commonNameData = new AsnEncodedData("CN", distinguishedName.RawData);
var commonName = commonNameData.Format(false);
if (!string.IsNullOrEmpty(commonName))
{
claims.Add(new Claim(ClaimTypes.Role, commonName));
}
}
//Get Emails
foreach (var email in result.Properties["mail"])
{
claims.Add(new Claim(ClaimTypes.Email, email.ToString()));
}
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
AuthenticationProperties authProperties = new()
{
AllowRefresh = true,
IssuedUtc = DateTime.Now,
ExpiresUtc = DateTimeOffset.Now.AddDays(1),
IsPersistent = true,
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
return Ok();
}
else
{
return NotFound("User Not Found!");
}
}
catch (Exception)
{
return NotFound("Login credentials is incorrect!");
}
}
[HttpPost]
[Route("authentication/logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
}
Login.razor
#page "/login"
#page "/login/{ErrorMessage}"
#layout CenteredBlockLayout
#attribute [AllowAnonymous]
<MudPaper Elevation="25" Class="pa-8" Width="100%" MaxWidth="500px">
<MudItem><img src="/images/logo.svg" alt="Logo" style="width:400px; height:50px;" /></MudItem>
<MudText Typo="Typo.h4" GutterBottom="true">Sign In</MudText>
<MudTextField #bind-Value="#Username" T="string" Label="Username"/>
<MudTextField #bind-Value="#Password" T="string" Label="Password"/>
<MudButton OnClick="(() => PerformLoginAsync())">Sign In</MudButton>
</MudPaper>
#if (!string.IsNullOrEmpty(ErrorMessage))
{
<MudAlert Severity="Severity.Error">#ErrorMessage</MudAlert>
}
Login.razor.cs
public partial class Login
{
public string Username { get; set; }
public string Password { get; set; }
[Parameter]
public string ErrorMessage { get; set; }
[Inject]
HttpClient Client { get; set; }
[Inject]
private NavigationManager NavMan { get; set; }
private async Task PerformLoginAsync()
{
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
{
UserCredentials cred = new UserCredentials
{
Username = Username,
Password = Password
};
var serialized = JsonConvert.SerializeObject(cred);
var stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");
using var result = await Client.PostAsync($"NavMan.BaseUri}authentication/login", stringContent);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
NavMan.NavigateTo("/", true);
}
else
{
ErrorMessage = await result.Content.ReadAsStringAsync();
}
}
}
}
I believe you need to append the cookie to the response. I haven't tested this with your code but it should work something like this:
HttpContext.Response.Cookies.Append("my_cookie", claimsString, new CookieOptions()
{
Domain = "mydomain.com",
SameSite = SameSiteMode.Lax,
Secure = true,
Path = "/",
Expires = DateTime.UtcNow.AddDays(1)
}
(These cookie options are just an example, of course. Tailor them to your specific needs.)
Keep in mind that you'll need to convert your claims to a string so that you can store it as the value in a cookie. In our case we store claims in a JWT, so that's what gets stored in the cookie. Here's how I do it:
public string CreateJWT(HttpContext httpContext, User user)
{
var handler = new JwtSecurityTokenHandler();
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[] {
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
new Claim(ClaimTypes.Email, user.Email),
}),
Expires = DateTime.UtcNow.AddMinutes(Config.AccessExpMins),
Issuer = Config.Issuer,
Audience = Config.Audience,
SigningCredentials = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256)
};
var token = handler.CreateJwtSecurityToken(descriptor);
var accessToken = handler.WriteToken(token);
httpContext.Response.Cookies.Append("my_cookie", accessToken, new CookieOptions()
{
Domain = Config.CookieDomain,
SameSite = SameSiteMode.Lax,
Secure = true,
Path = "/",
Expires = DateTime.UtcNow.AddMinutes(Config.AccessExpMins)
});
return accessToken;
}
As for parsing the JWT, I'm sure there are a number of ways to go about it. The one that worked for me was this one.
How to send a proper http request from android using volly for a post REST URL created with using aws api gateway?
How to make a proper http request from android so that these values accept by api gateway.
Api gateway internal testing works properly.
This is the parameter need to pass through the request.
{
"id": "22",
"res": "10",
"rate": "75",
"index": "1"
}
//this method is used call http request
public static void newPost2(Context context){
String awsAccessKey = "awsAccessKey";
final String awsSecretKey = "awsSecretKey";
String dateStr = ClientSSLSocketFactory.getServerTime();
String scope = dateStr + "/us-east-1/execute-api/aws4_request,";
String headerNames = "host;x-amz-date";
final String credentialsAuthorizationHeader = "Credential=" + awsAccessKey + "/" + scope;
String signedHeadersAuthorizationHeader = "SignedHeaders=" + headerNames;
String signatureAuthorizationHeader = "Signature=" + "hex encoded signature";
final String authorization = "AWS4-HMAC-SHA256 "
+ credentialsAuthorizationHeader + ", "
+ signedHeadersAuthorizationHeader + ", "
+ signatureAuthorizationHeader;
final String url="https://xxxxxxx2.execute-api.us-east-1.amazoxxxxxxxxxxxxxxxx";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// mPostCommentResponse.requestCompleted();
System.out.print("\n\n\n......post ok."+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// mPostCommentResponse.requestEndedWithError(error);
System.out.print("\n\n\n.......post error."+error);
error.printStackTrace();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=utf-8");
params.put("id","22");
params.put("rate","10");
params.put("res", "75");
params.put("index","1");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
// params.put("Content-Type","application/x-www-form-urlencoded");
params.put("Host", "apigateway.us-east-1.amazonaws.com");
params.put("x-amz-date", ClientSSLSocketFactory.getawsnettime());
params.put("Authorization", authorization);
params.put("Content-Type", "application/x-amz-json-1.0");
return params;
}
};
queue.add(sr);
}
but shows error in log
...stringr..header......post error.com.android.volley.AuthFailureError
11-30 14:52:14.140 4663-4663/com.example.acernrc.noveleven W/System.err: com.android.volley.ServerError
11-30 14:52:14.140 4663-4663/com.example.acernrc.noveleven W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163)
I have build a client, that should fetch data from a remote, wsdl-based webservice (using SOAP).
But everytime I try to connect (with a call of a function) with the service I get the following exception:
org.springframework.ws.soap.client.SoapFaultClientException: Username and/or Password cannot be null
at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:38) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:826) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:621) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at com.test.adminUI.myPartners.client.MyPartnersServiceClient.sendSoapRequest(MyPartnersServiceClient.java:113) [bin/:na]
at com.test.adminUI.myPartners.client.MyPartnersServiceClient.findUser(PartnersServiceClient.java:70) [bin/:na]...
If I put a wrong password for example, the service registered it, an throws a Unauthorized 401 ERROR
So that mean, it actually validates my useraccount details.
my client:
public class MyServiceClient extends WebServiceGatewaySupport {
#Autowired
private ObjectFactory factory;
#Autowired
private SoapProperties adProperties;
private static final String WS_ADDRESSING_URI = "http://www.w3.org/2005/08/addressing";
private static final String TO_TAG = "To";
private static final String ACTION_TAG = "Action";
private static final String WSA_PREFIX = "wsa";
private static final String SOAP_ACTION_FIND_IFXPERSON = adProperties.getsoapURL();
public List<Person> findUser(String email, String globalID) {
List<Person> list = null;
FindPerson findperson = new FindPerson();
try {
findperson.setGlobalID(factory.createGlobalID(globalID));
findperson.setServiceUsername(factory.createServiceUsername(adProperties.getServiceUser()));
findperson.setServicePassword(factory.createServicePassword(adProperties.getServicePassword()));
FindPersonResponse response = (FindPersonResponse) sendSoapRequest(
SOAP_ACTION_FIND_PERSON, findperson);
list = response.getFindPersonResult().getValue();
} catch (Exception ex) {
log.error("could not find Person: ", ex);
}
return null;
}
private Object sendSoapRequest(final String soapAction, Object payLoad) {
Object response = null;
try {
Credentials auth = new NTCredentials(adProperties.getAuthUser(),
adProperties.getAuthPassword(), null, adProperties.getAuthDomain());
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, auth);
clientBuilder.setDefaultCredentialsProvider(credsProvider);
RemoveSoapHeadersInterceptor interceptor = new RemoveSoapHeadersInterceptor();
clientBuilder.addInterceptorFirst(interceptor);
HttpClient httpClient = clientBuilder.build();
HttpComponentsMessageSender messageSender = new HttpComponentsMessageSender();
messageSender.setHttpClient(httpClient);
messageSender.setCredentials(auth);
messageSender.afterPropertiesSet();
getWebServiceTemplate().setMessageSender(messageSender);
SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory(
MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL));
getWebServiceTemplate().setMessageFactory(messageFactory);
response = getWebServiceTemplate().marshalSendAndReceive(
adProperties.getServiceEndpoint(), payLoad, new SoapActionCallback(soapAction) {
public void doWithMessage(WebServiceMessage message) {
try {
SaajSoapMessage soapMessage = (SaajSoapMessage) message;
SOAPMessage saajMessage = soapMessage.getSaajMessage();
SOAPEnvelope envelope = saajMessage.getSOAPPart().getEnvelope();
SOAPHeader header = envelope.getHeader();
QName wsaToQName = new QName(WS_ADDRESSING_URI, TO_TAG, WSA_PREFIX);
SOAPHeaderElement wsaTo = header.addHeaderElement(wsaToQName);
wsaTo.setTextContent(adProperties.getServiceEndpoint());
QName wsaActionQName = new QName(WS_ADDRESSING_URI, ACTION_TAG,
WSA_PREFIX);
SOAPHeaderElement wsaAction = header
.addHeaderElement(wsaActionQName);
wsaAction.setTextContent(soapAction);
} catch (Exception e) {
log.error("", e);
}
}
});
} catch (Exception ex) {
log.error(ex);
}
return response;
}
}
Configuration:
#Configuration
public class MyPartnersServiceConfiguration {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("com.test.adminUI.myPartners.wsdl");
return marshaller;
}
#Bean
public IFXPartnersServiceClient iFXPartnersServiceClient(Jaxb2Marshaller marshaller) {
IFXPartnersServiceClient client = new IFXPartnersServiceClient();
client.setDefaultUri("http://test.idms.partnersservice");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
Does anybody know what i have to do?
Thanks in advance!
UPDATE
I forgot to mention, that I also get a warning in my console:
o.a.http.impl.auth.HttpAuthenticator: NEGOTIATE authentication error: No valid credentials provided (Mechanism level: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt))
Is this the problem? What do I have to do in this case?
#Bean
public IFXPartnersServiceClient iFXPartnersServiceClient(Jaxb2Marshaller marshaller) {
IFXPartnersServiceClient client = new IFXPartnersServiceClient();
client.setDefaultUri("http://test.idms.partnersservice");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
//Set messageSender to client
client.setMessageSender(httpComponentsMessageSender());
return client;
}
I want to use cookies in Robospice, I have spice service:
public class JsonSpiceService extends SpringAndroidSpiceService {
public RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
restTemplate.setRequestFactory( httpRequestFactory );
listHttpMessageConverters.add(jsonConverter);
listHttpMessageConverters.add(formHttpMessageConverter);
listHttpMessageConverters.add(stringHttpMessageConverter);
restTemplate.setMessageConverters(listHttpMessageConverters);
return restTemplate;
}
public CacheManager createCacheManager(Application application) throws CacheCreationException {
CacheManager cacheManager = new CacheManager();
List< Class< ? >> classCollection = new ArrayList< Class< ? >>();
classCollection.add(User.class);
JacksonObjectPersisterFactory jacksonObjectPersisterFactory = new JacksonObjectPersisterFactory(application);
cacheManager.addPersister(jacksonObjectPersisterFactory);
return cacheManager;
}
}
and my Request class:
public class Request extends SpringAndroidSpiceRequest<HttpModel> {
private Context context;
private HttpMethod httpMethod;
private MultiValueMap<String, String> body;
private String link;
private String what;
private Object object;
public Request(Context context, HttpMethod httpMethod, MultiValueMap<String, String> body, String link, String what, Object object) {
super(HttpModel.class);
this.context = context;
this.httpMethod = httpMethod;
this.body = body;
this.link = link;
this.what = what;
this.object = object;
}
#Override
public HttpModel loadDataFromNetwork() throws Exception {
HttpModel httpModel;
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> requestEntity;
if (!what.equals(LOGIN)) {
headers.setContentType(MediaType.APPLICATION_JSON);
} else {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
}
requestEntity = new HttpEntity<Object>(body, headers);
ResponseEntity<HttpModel> responseEntity = getRestTemplate().exchange(link, httpMethod, requestEntity, HttpModel.class);
httpModel = responseEntity.getBody();
return httpModel;
}
}
How can i get cookie from response?I try add CookieManager to my Request class, but dont'work:
final CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
In postman Cookie look like this:
enter link description here
CookieManager is used only for managing cookies in your application's WebViews.
You can use responseEntity.getHeaders().get(COOKIE). You can also try SET_COOKIE or SET_COOKIE2 keys instead of COOKIE, depending on your server's response.