URLConnection cannot read any header fields but firefox does - java

I'm trying to get header fields from this url using URLConnection in java
https://farm9.staticflickr.com/8709/16206420933_5d7427b8e3_o_d.jpg
URL fUrl = new URL(url);
URLConnection connection = fUrl.openConnection();
for (Map.Entry<String, List<String>> k : connection.getHeaderFields().entrySet()) {
System.out.println(k.toString());
}//Return nothing
But i can't get any fields from this link while firefox have the conent-length, accept-ranges ...
HTTP/1.1 200 OK
Date: Wed, 18 Mar 2015 02:44:58 GMT
Content-Type: image/jpeg
Content-Length: 11734133
p3p: policyref="http://info.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE LOC GOV"
x-photo-origin: gq1
Content-Disposition: attachment; filename=16206420933_5d7427b8e3_o.jpg
Pragma: no-cache
Expires: 0
Last-Modified: Sun, 15 Mar 2015 20:53:26 GMT
Accept-Ranges: bytes
Age: 0
Via: http/1.1 photocache907.flickr.gq1.yahoo.com (ApacheTrafficServer [cMsSf ]), http/1.1 cache127.flickr.sg3.yahoo.com (ApacheTrafficServer [cMsSf ])
Server: ATS
ytracetag: 000100080000000100000000000000003e5ac2bfd747bd07000000000000000013cc77a17690ed0013cc77a183c7b900592ecf220000000022cf2e594d34a5ef
X-Firefox-Spdy: 3.1
So what can i do in this case, thanks for the help.

There aren't any header fields until you call connect(), getInputStream(), or getResponseCode().

Related

#RequestMapping handling of special characters

I have a REST API
#RequestMapping(value = "/Save", method = RequestMethod.POST,
consumes = {"application/json;charset=ISO-8859-1" },
produces = {"application/json;charset=ISO-8859-1" })
public SaveResponse save(#RequestBody SaveRequest request) {
//some codes
}
}
My request contains the following lines
{
:
:
"mailingAddress": {
"addressLine1": "Carrera 36E N°",
"addressLine2": "Medellín, Antioquia",
"country": "COL"
}
:
And I received a 400 Bad Request
HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Date: Wed, 16 Jun 2021 12:26:37 GMT
Pragma: no-cache
Content-Length: 0
Expires: 0
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-RBT-Optimized-By: CANA014IJT (RiOS 6.1.1a #11) SC
And when I removed the characters "°" and "í" from the request, then the request can go through with no error. What is my problem?
Thank you.
You can try changing the character set from ISO-8859-1 to UTF-8, as the former does not support as wide an array of character mappings (What is the difference between UTF-8 and ISO-8859-1?).

Caffeine cache in Play Framework doesn't return cached responses

I'm using Caffeine cache implementation with my java Play Framework job to cache outgoing http requests, and I see that in spite of the fact that the cache is up and running, my service still hit the external server every time instead of returning the value from the cache.
And I see that the key logged in the logs is always the same.
So I see freshnessLifetime is not set, so it might mean that the cache expires immediately. but I still don't know how to set it in the config
I have not changed my java code and I cannot find any examples if I need to do that, or I'm only supposed to have a config for cache working for all outgoing requests.
I would appreciate any help with this
My build.sbt contains:
libraryDependencies += ws
libraryDependencies += caffeine
My reference.conf contains:
# Configuration settings for JSR 107 Cache for Play WS.
play.ws.cache {
enabled = true
heuristics.enabled = false
name = "play-ws-cache"
}
My application.conf contains:
# source https://github.com/ben-manes/caffeine/blob/master/jcache/src/main/resources/reference.conf
caffeine.jcache {
# A named cache is configured by nesting a new definition under the caffeine.jcache namespace. The
# per-cache configuration is overlaid on top of the default configuration.
play-ws-cache {
read-through {
# If enabled, the entry is loaded automatically on a cache miss
enabled = true
}
# The eviction policy for automatically removing entries from the cache
policy {
# The expiration threshold before lazily evicting an entry. This single threshold is reset on
# every operation where a duration is specified. As expected by the specification, if an entry
# expires but is not accessed and no resource constraints force eviction, then the expired
# entry remains in place.
lazy-expiration {
# The duration before a read of an entry is considered expired. If set to 0 then the entry
# is considered immediately expired. May be a time duration, null to indicate no change, or
# "eternal" to indicate no expiration.
access = 5m
}
# The expiration thresholds before eagerly evicting an entry. These settings correspond to the
# expiration supported natively by Caffeine where expired entries are collected during
# maintenance operations.
eager-expiration {
# Specifies that each entry should be automatically removed from the cache once a fixed
# duration has elapsed after the entry's creation, the most recent replacement of its value,
# or its last read. Access time is reset by all cache read and write operation. This setting
# cannot be combined with the variable configuration.
after-access = 5m
}
# The maximum bounding of the cache based upon its logical size
maximum {
# The maximum number of entries that can be held by the cache. This setting cannot be
# combined with the weight configuration.
size = 10000
}
}
}
}
I see in the logs this:
[debug] - restclient.BaseRestClient - Executing GET with url
http://localhost:9001/entities/v2/867386732 [trace] -
p.a.l.w.a.c.CachingAsyncHttpClient - execute: request = Request(GET
http://localhost:9001/entities/v2/867386732), handler =
AsyncHandler(play.libs.ws.ahc.StandaloneAhcWSClient$ResponseAsyncCompletionHandler#65b0b233),
future = null [debug] - p.a.libs.ws.ahc.cache.AhcHttpCache - get: key
= GET http://localhost:9001/entities/v2/867386732 [debug] - p.a.l.w.a.c.CachingAsyncHttpClient - execute GET
http://localhost:9001/entities/v2/867386732: results =
List(ResponseEntry(CacheableResponse(status =
CacheableHttpResponseStatus(code = 200, text = OK), headers =
DefaultHttpHeaders[Referrer-Policy: origin-when-cross-origin,
strict-origin-when-cross-origin, X-Frame-Options: DENY,
X-XSS-Protection: 1; mode=block, X-Content-Type-Options: nosniff,
X-Permitted-Cross-Domain-Policies: master-only, Date: Thu, 01 Oct 2020
17:44:08 GMT, Content-Type: application/json, Content-Length: 2144],
bodyParts size =
1),GET,Map(),Some(2020-10-02T10:44:08.760450-07:00[America/Los_Angeles])))
[trace] - c.t.c.ResponseSelectionCalculator - findMatchingResponse:
request =
CacheRequest(http://localhost:9001/entities/v2/867386732,GET,TreeMap()),
responses =
List(StoredResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:08 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only)),GET,Map()))
[debug] - p.a.l.w.a.c.CachingAsyncHttpClient - execute GET
http://localhost:9001/entities/v2/867386732: selected from cache:
ResponseEntry(CacheableResponse(status =
CacheableHttpResponseStatus(code = 200, text = OK), headers =
DefaultHttpHeaders[Referrer-Policy: origin-when-cross-origin,
strict-origin-when-cross-origin, X-Frame-Options: DENY,
X-XSS-Protection: 1; mode=block, X-Content-Type-Options: nosniff,
X-Permitted-Cross-Domain-Policies: master-only, Date: Thu, 01 Oct 2020
17:44:08 GMT, Content-Type: application/json, Content-Length: 2144],
bodyParts size =
1),GET,Map(),Some(2020-10-02T10:44:08.760450-07:00[America/Los_Angeles]))
[trace] - c.t.c.CurrentAgeCalculator - calculateCurrentAge(headers:
TreeMap(Date -> List(Thu, 01 Oct 2020 17:44:08 GMT), Content-Type ->
List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only)), now:
2020-10-01T17:44:38.690992Z[GMT], requestTime:
2020-10-01T17:44:38.690274Z[GMT], responseTime:
2020-10-01T17:44:38.690981Z[GMT]) [trace] - c.t.c.CurrentAgeCalculator
calculateCurrentAge: currentAge = PT30S [debug] - c.t.c.ResponseServingCalculator - serveResponse: response found for
'GET http://localhost:9001/entities/v2/867386732', age = 30 [trace] -
c.t.c.ResponseServingCalculator - noCacheFound: request =
CacheRequest(http://localhost:9001/entities/v2/867386732,GET,TreeMap()),
response =
StoredResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:08 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only)),GET,Map())
[trace] - c.t.c.ResponseServingCalculator - isCachedResponseFresh:
request =
CacheRequest(http://localhost:9001/entities/v2/867386732,GET,TreeMap()),
response =
StoredResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:08 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only)),GET,Map())
[trace] - c.t.c.FreshnessCalculator - calculateFreshnessLifetime:
[debug] - c.t.c.FreshnessCalculator - calculateFreshnessLifetime:
freshnessLifetime = None [debug] - c.t.c.FreshnessCalculator -
calculateFreshnessLifetime: result = PT0S [debug] -
c.t.c.ResponseServingCalculator - isCachedResponseFresh:
freshnessLifetime = PT0S, currentAge = PT30S [debug] -
c.t.c.ResponseServingCalculator - isCachedResponseFresh:
freshnessLifetime = PT0S, currentAge = PT30S [trace] -
c.t.c.ResponseServingCalculator - isStaleResponseProhibited: request =
CacheRequest(http://localhost:9001/entities/v2/867386732,GET,TreeMap()),
response =
StoredResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:08 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only)),GET,Map())
[trace] - c.t.c.ResponseServingCalculator - isStaleResponseAllowed:
PT30S, request =
CacheRequest(http://localhost:9001/entities/v2/867386732,GET,TreeMap()),
response =
StoredResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:08 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only)),GET,Map())
[debug] - c.t.c.ResponseServingCalculator - isStaleResponseAllowed:
stale response not allowed [trace] - c.t.c.ResponseServingCalculator -
canServeStaleAndRevalidate: response =
StoredResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:08 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only)),GET,Map())
[trace] - c.t.c.FreshnessCalculator - calculateFreshnessLifetime:
[debug] - c.t.c.FreshnessCalculator - calculateFreshnessLifetime:
freshnessLifetime = None [debug] - c.t.c.FreshnessCalculator -
calculateFreshnessLifetime: result = PT0S [trace] -
c.t.c.FreshnessCalculator - calculateFreshnessLifetime: [debug] -
c.t.c.FreshnessCalculator - calculateFreshnessLifetime:
freshnessLifetime = None [debug] - c.t.c.FreshnessCalculator -
calculateFreshnessLifetime: result = PT0S [debug] -
p.a.l.w.a.c.CachingAsyncHttpClient - serveResponse GET
http://localhost:9001/entities/v2/867386732: Response is stale, and
stale response is not allowed -- revalidate with staleIfError = false
[trace] - p.a.l.w.a.c.CachingAsyncHttpClient - buildValidationRequest:
Request(GET http://localhost:9001/entities/v2/867386732), response =
CacheableResponse(status = CacheableHttpResponseStatus(code = 200,
text = OK), headers = DefaultHttpHeaders[Referrer-Policy:
origin-when-cross-origin, strict-origin-when-cross-origin,
X-Frame-Options: DENY, X-XSS-Protection: 1; mode=block,
X-Content-Type-Options: nosniff, X-Permitted-Cross-Domain-Policies:
master-only, Date: Thu, 01 Oct 2020 17:44:08 GMT, Content-Type:
application/json, Content-Length: 2144], bodyParts size = 1) [debug] -
p.s.a.o.a.n.r.NettyRequestSender - Using pooled Channel '[id:
0x1fac35f7, L:/127.0.0.1:49899 - R:localhost/127.0.0.1:9001]' for
'GET' to 'http://localhost:9001/entities/v2/867386732' [debug] -
p.s.a.o.a.n.r.NettyRequestSender - Using open Channel [id: 0x1fac35f7,
L:/127.0.0.1:49899 - R:localhost/127.0.0.1:9001] for GET
'/entities/v2/867386732' [trace] - p.s.a.i.n.h.logging.LoggingHandler
[id: 0x1fac35f7, L:/127.0.0.1:49899 - R:localhost/127.0.0.1:9001] WRITE: 107B
[debug] - p.s.a.o.a.netty.handler.HttpHandler -
Request DefaultFullHttpRequest(decodeResult: success, version:
HTTP/1.1, content: EmptyByteBufBE) GET /entities/v2/867386732 HTTP/1.1
host: localhost:9001 accept: / user-agent: AHC/2.1
Response DefaultHttpResponse(decodeResult: success, version: HTTP/1.1)
HTTP/1.1 200 OK Referrer-Policy: origin-when-cross-origin,
strict-origin-when-cross-origin X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff
X-Permitted-Cross-Domain-Policies: master-only Date: Thu, 01 Oct 2020
17:44:38 GMT Content-Type: application/json Content-Length: 2144
[debug] - p.s.a.o.a.n.channel.ChannelManager - Adding key:
http://localhost:9001 for channel [id: 0x1fac35f7, L:/127.0.0.1:49899
R:localhost/127.0.0.1:9001] [trace] - p.a.l.w.a.cache.AsyncCachingHandler - onCompleted: this =
CacheAsyncHandler(key = GET
http://localhost:9001/entities/v2/867386732, requestTime =
2020-10-01T17:44:38.692247Z[GMT], builder =
play.api.libs.ws.ahc.cache.CacheableResponseBuilder#492a840f,
asyncHandler =
AsyncHandler(play.libs.ws.ahc.StandaloneAhcWSClient$ResponseAsyncCompletionHandler#65b0b233)})
[debug] - p.a.l.w.a.cache.AsyncCachingHandler - onCompleted: response
= CacheableResponse(status = CacheableHttpResponseStatus(code = 200, text = OK), headers = DefaultHttpHeaders[Referrer-Policy:
origin-when-cross-origin, strict-origin-when-cross-origin,
X-Frame-Options: DENY, X-XSS-Protection: 1; mode=block,
X-Content-Type-Options: nosniff, X-Permitted-Cross-Domain-Policies:
master-only, Date: Thu, 01 Oct 2020 17:44:38 GMT, Content-Type:
application/json, Content-Length: 2144], bodyParts size = 1) [trace] -
p.a.libs.ws.ahc.cache.AhcHttpCache - invalidate: request = Request(GET
http://localhost:9001/entities/v2/867386732), response =
CacheableResponse(status = CacheableHttpResponseStatus(code = 200,
text = OK), headers = DefaultHttpHeaders[Referrer-Policy:
origin-when-cross-origin, strict-origin-when-cross-origin,
X-Frame-Options: DENY, X-XSS-Protection: 1; mode=block,
X-Content-Type-Options: nosniff, X-Permitted-Cross-Domain-Policies:
master-only, Date: Thu, 01 Oct 2020 17:44:38 GMT, Content-Type:
application/json, Content-Length: 2144], bodyParts size = 1) [debug] -
p.a.l.w.a.cache.AsyncCachingHandler - processFullResponse:
fullResponse = CacheableResponse(status =
CacheableHttpResponseStatus(code = 200, text = OK), headers =
DefaultHttpHeaders[Referrer-Policy: origin-when-cross-origin,
strict-origin-when-cross-origin, X-Frame-Options: DENY,
X-XSS-Protection: 1; mode=block, X-Content-Type-Options: nosniff,
X-Permitted-Cross-Domain-Policies: master-only, Date: Thu, 01 Oct 2020
17:44:38 GMT, Content-Type: application/json, Content-Length: 2144],
bodyParts size = 1) [trace] - c.t.c.ResponseCachingCalculator -
isCacheable: request:
CacheRequest(http://localhost:9001/entities/v2/867386732,GET,TreeMap()),
response =
OriginResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:38 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only))) [trace] -
c.t.c.ResponseCachingCalculator - responseIsCacheable: response =
OriginResponse(http://localhost:9001/entities/v2/867386732,200,TreeMap(Date
-> List(Thu, 01 Oct 2020 17:44:38 GMT), Content-Type -> List(application/json), Content-Length -> List(2144), Referrer-Policy
-> List(origin-when-cross-origin, strict-origin-when-cross-origin), X-Frame-Options -> List(DENY), X-XSS-Protection -> List(1;
mode=block), X-Content-Type-Options -> List(nosniff),
X-Permitted-Cross-Domain-Policies -> List(master-only))) [trace] -
c.t.c.ResponseCachingCalculator - isCacheable: result =
DoCacheResponse(Response status code 200 is cacheable by default)
[debug] - p.a.l.w.a.cache.AsyncCachingHandler - isCacheable: DO CACHE,
because Response status code 200 is cacheable by default [debug] -
p.a.libs.ws.ahc.cache.AhcHttpCache - cacheResponse: response =
CacheableResponse(status = CacheableHttpResponseStatus(code = 200,
text = OK), headers = DefaultHttpHeaders[Referrer-Policy:
origin-when-cross-origin, strict-origin-when-cross-origin,
X-Frame-Options: DENY, X-XSS-Protection: 1; mode=block,
X-Content-Type-Options: nosniff, X-Permitted-Cross-Domain-Policies:
master-only, Date: Thu, 01 Oct 2020 17:44:38 GMT, Content-Type:
application/json, Content-Length: 2144], bodyParts size = 1) [debug] -
p.a.libs.ws.ahc.cache.AhcHttpCache - cacheResponse: strippedResponse =
CacheableResponse(status = CacheableHttpResponseStatus(code = 200,
text = OK), headers = DefaultHttpHeaders[Referrer-Policy:
origin-when-cross-origin, strict-origin-when-cross-origin,
X-Frame-Options: DENY, X-XSS-Protection: 1; mode=block,
X-Content-Type-Options: nosniff, X-Permitted-Cross-Domain-Policies:
master-only, Date: Thu, 01 Oct 2020 17:44:38 GMT, Content-Type:
application/json, Content-Length: 2144], bodyParts size = 1) [trace] -
c.t.c.SecondaryKeyCalculator - calculate: request =
CacheRequest(http://localhost:9001/entities/v2/867386732,GET,TreeMap()),
responseHeaders = TreeMap(Date -> List(Thu, 01 Oct 2020 17:44:38 GMT),
Content-Type -> List(application/json), Content-Length -> List(2144),
Referrer-Policy -> List(origin-when-cross-origin,
strict-origin-when-cross-origin), X-Frame-Options -> List(DENY),
X-XSS-Protection -> List(1; mode=block), X-Content-Type-Options ->
List(nosniff), X-Permitted-Cross-Domain-Policies -> List(master-only))
[debug] - p.a.libs.ws.ahc.cache.AhcHttpCache - put: key = GET
http://localhost:9001/entities/v2/867386732, entry =
ResponseEntry(CacheableResponse(status =
CacheableHttpResponseStatus(code = 200, text = OK), headers =
DefaultHttpHeaders[Referrer-Policy: origin-when-cross-origin,
strict-origin-when-cross-origin, X-Frame-Options: DENY,
X-XSS-Protection: 1; mode=block, X-Content-Type-Options: nosniff,
X-Permitted-Cross-Domain-Policies: master-only, Date: Thu, 01 Oct 2020
17:44:38 GMT, Content-Type: application/json, Content-Length: 2144],
bodyParts size =
1),GET,Map(),Some(2020-10-02T10:44:38.771750-07:00[America/Los_Angeles]))
[debug] - restclient.BaseRestClient - Response status [200] for url
[http://localhost:9001/entities/v2/867386732] [trace] -
p.s.a.i.n.h.logging.LoggingHandler - [id: 0x1fac35f7,
L:/127.0.0.1:49899 - R:localhost/127.0.0.1:9001] READ COMPLETE [trace]
p.a.l.w.ahc.cache.CacheableResponse - getResponseBody:
I actually found how it works. The cache is not supposed to manage the lifetime like it does a separate service like Redis or Memcached but instead it acts like a browser does and is managed by the headers in HTTP response.
Here: https://github.com/playframework/cachecontrol/blob/e4694aa0665e2ccc5030ae1cf1d0b15ad5b98471/src/main/scala/com/typesafe/play/cachecontrol/FreshnessCalculator.scala#L42
So the solution for me was to change the server so it serves correct header: Cache-Control "max-age=3600, public"

Java HttpURLConnection - enumerate all 302 redirect hops

my goal is to use java.net.HttpURLConnection in order to parse all the 302 redirect hops for a given URL.
This is my snippet code (I'm actually using it in Talend SW):
String url = row2.url;
java.net.HttpURLConnection con = (java.net.HttpURLConnection) new java.net.URL(url).openConnection();
con.setInstanceFollowRedirects(false);
con.connect();
String realURL = con.getHeaderField("Location");
System.out.println(realURL);
It works pretty well if there's only one 302 reply.
For instance if I populate row2.ulr= "https://jigsaw.w3.org/HTTP/300/302.html" the code will output -> https://jigsaw.w3.org/HTTP/300/Overview.html witch is 100% correct.
My problem is that I'm unable to parse several 302 reply, a typical example is the Facebook URL:
www.facebook.com/ID_account ->redirect-> www.facebook.com/ACCOUNT_NAME
Using a redirect checker online I found 2 - 302 response (I need the second one):
This is the CURL output:
> >>> http://www.facebook.com/123456789
>
> > --------------------------------------------
> > 302 Found
> > --------------------------------------------
>
> Status: 302 Found Code: 302
> Location: https://www.facebook.com/123456789 Vary: Accept-Encoding
> Content-Type: text/html; charset=UTF-8
> X-FB-Debug: Muf4PfCP9TRKCO17QUf7SV2vsdnrCu6Gw2+sjWAKe0QPGdAToJPcmgH5LHv3NIAhzsJXfPB3a9/mVtuhiiEihA==
> Date: Mon, 16 Oct 2017 16:02:55 GMT Connection: close
> Content-Length: 0
>
>
>
>
> >>> https://www.facebook.com/123456789
>
> > --------------------------------------------
> > 302 Found
> > --------------------------------------------
>
> Status: 302 Found Code: 302 X-XSS-Protection: 0
> public-key-pins-report-only: max-age=600;
> pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=";
> pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws=";
> pin-sha256="gMxWOrX4PMQesK9qFNbYBxjBfjUvlkn/vN1n+L9lE5E=";
> pin-sha256="q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ=";
> report-uri="http://reports.fb.com/hpkp/" Pragma: no-cache
> Location: https://www.facebook.com/a_name_account/
> Cache-Control: private, no-cache, no-store, must-revalidate
> X-Frame-Options: DENY Strict-Transport-Security: max-age=15552000;
> preload X-Content-Type-Options: nosniff Expires: Sat, 01 Jan 2000
> 00:00:00 GMT Vary: Accept-Encoding Content-Type: text/html;
> charset=UTF-8
> X-FB-Debug: j2KCBNZ1poIJ0xUeeQYbinpcqq2avoI4z8eWb9Dx/yUUg98uyGYGadydia7en1s5X4DJeaJB7VjxYaRvP+psCw==
> Date: Mon, 16 Oct 2017 16:02:55 GMT Connection: close
> Content-Length: 0
>
>
>
>
> >>> https://www.facebook.com/a_name_account/
Any suggestion on how to find the second 302 "Location" ->https://www.facebook.com/a_name_account/?
Thanks in advance
Regs
S.
This would be great behavior for a Recursive Method.
You could keep calling your method if you determine that there is still a location in the response header.
public void recurseLocation(String url) {
URL url = new URL(location);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.connect();
String newLocation = connection.getHeaderField("Location");
if (newLocation != null) {
newLocation = recurseLocation(newLocation);
} else {
newLocation = location;
}
return newLocation;
}

Angular2 - unable to get Set-Cookie from auth. response (jaas, wf)

Iam trying to authenticate from Angular2.1.0 to JAAS form-based j2ee app on WildFly 8.2
let j_username = 'sb2';
let j_password = 'sb222';
let url: string = 'http://127.0.0.1:8888/prototype-rest/j_security_check';
let body = 'j_username=' + j_username + '&j_password=' + j_password;
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
;
//let options = new RequestOptions({headers: headers, withCredentials : true});
let options = new RequestOptions({headers: headers});
this.http.post(url, body, options)
.subscribe(
(res: Response) => {
console.log('res = ' + res);
console.log(res.headers.keys());
var headers = res.headers;
var setCookieHeader = headers.get('Set-Cookie');
console.log('setCookieHeader = ' + setCookieHeader);
},
err => {
console.log('err = ' + err);
}
)
;
response from wildfly
HTTP/1.1 200 OK
Expires: 0
Cache-Control: no-cache, no-store, must-revalidate
X-Powered-By: Undertow/1
Set-Cookie: JSESSIONID=iyD6Yz_Tj7xsIM1zRDHaR2bh.sk-za-04702; path=/prototype-rest
Access-Control-Allow-Headers: accept, authorization, content-type, x-requested-with
Server: WildFly/8
Pragma: no-cache
Access-Control-Expose-Headers: Set-Cookie
Date: Thu, 03 Nov 2016 14:01:41 GMT
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 0
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT
Access-Control-Max-Age: 3600
My problem is that I am not able to read Set-Cookie, if I use withCredentials : true (I am not sure if I should), response fails ... I'd like to add JSESSIONID to request, where I register websocket ...

Jersey can't add parameter when post submit

I'm using Jersey 2.4.1
I dont know. Why i can't add parameter when post submit.
Parameter information should print at line number 5 in my think.
my sample code is below
#Test
public void test() {
Client client = ClientBuilder.newClient();
client.register(new LoggingFilter());
WebTarget target = client.target("http://stackoverflow.com/");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(form));
}
result logging is..
1 * LoggingFilter - Request received on thread main
1 > POST http://stackoverflow.com/
1 > Accept: application/json
1 > Content-Type: application/x-www-form-urlencoded
2 * LoggingFilter - Response received on thread main
2 < 200
2 < X-Frame-Options: SAMEORIGIN
2 < Date: Mon, 02 Dec 2013 14:13:35 GMT
2 < Vary: *
2 < Content-Length: 195990
2 < Expires: Mon, 02 Dec 2013 14:14:35 GMT
2 < Last-Modified: Mon, 02 Dec 2013 14:13:35 GMT
2 < Content-Type: text/html; charset=utf-8
2 < Pragma: no-cache
2 < Cache-Control: public, max-age=60
To print form parameters to console log you need to instantiate LoggingFilter using other constructor than the default one, see LoggingFilter(java.util.logging.Logger, boolean):
client.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
This behavior might be different from the one present in Jersey 1.x.

Categories