Sorry if the question is possibly repeated. I'm not familiar with Java and I'm stuck with a Cordova plugin which returns headers in a non-JSON structure which I think is Map.soString() presentation of request.headers()
//These parts works fine returning response body
HttpRequest request = HttpRequest.post(this.getUrlString());
this.setupSecurity(request);
request.headers(this.getHeaders());
request.acceptJson();
request.contentType(HttpRequest.CONTENT_TYPE_JSON);
request.send(getJsonObject().toString());
int code = request.code();
String body = request.body(CHARSET);
JSONObject response = new JSONObject();
response.put("status", code);
// in this line I must put JSON converted headers instead of request.headers()
response.put("headers", request.headers());
I've tried
String headers = request.headers().toString();
and
JSONObject headers = new JSONObject(request.headers());
to change the aforementioned line to
response.put("headers", headers);
but none of them worked.
How should I send headers as JSON in response?
More context:
Currently the response headers are:
{
null=[HTTP/1.0 200 OK],
Content-Type=[application/json],
Date=[Mon, 25 Jan 2016 07:47:31 GMT],
Server=[WSGIServer/0.1 Python/2.7.6],
Set-Cookie=[csrftoken=tehrIvP7gXzfY3F9CWrjbLXb2uGdwACn; expires=Mon, 23-Jan-2017 07:47:31 GMT; Max-Age=31449600; Path=/, sessionid=iuza9r2wm3zbn07aa2mltbv247ipwfbs; expires=Mon, 08-Feb-2016 07:47:31 GMT; httponly; Max-Age=1209600; Path=/],
Vary=[Accept, Cookie],
X-Android-Received-Millis=[1453708294595],
X-Android-Sent-Millis=[1453708294184], X-Frame-Options=[SAMEORIGIN]
}
and are sent in body of response. so I need to parse them, but I can't do.
This should be the way to do it:
JSONObject headers = new JSONObject(request.headers());
However, the "toString()" display of the headers seem to be showing a map entry with a null key. That won't work in JSON: an JSON object attribute name cannot be null. My guess is that the null key caused the crash.
So I think you need to filter out the "bad" entry; i.e. code it something like this:
JSONObject headers = new JSONObject()
for (Map.Entry entry: request.headers().entries()) {
if (entry.getKey() != null) {
headers.put(entry.getKey(), entry.getValue());
}
}
Related
I'm new to spring boot application. I want to get the response from there in string. this is my code.
String accessURL = serverURL + "itim/rest/accesscategories";
RestClient rc4 = new RestClient(ResourceBuilder.getClientConfig());
Resource r4 = rc4.resource(accessURL);
r4.cookie(ltpaToken);
r4.cookie(jsessionid);
r4.cookie(csrftoken);
r4.header("Content-Type", "application/json");
ClientResponse resp4 = r4.get();
right now i'm doing this:
System.out.println(resp4.getStatusCode());
System.out.println(resp4.getStatusType());
System.out.println(resp4.getHeaders());
and i get this responce:
200
OK
CaseInsensitiveMultivaluedMap [map=[Cache-Control=no-cache,no-store,max-age=0,Content-
Language=en-US,Content-Type=application/vnd.ibm.isim-v1+json,Date=Sat, 24 Apr 2021 02:22:32
GMT,Expires=Thu, 01 Jan 1970 00:00:00 GMT,Pragma=No-cache,Set-
Cookie=com.ibm.isim.lastActivity=Bj7WAcMo3apevFKD4JoHyr4iKepdA8AVptb3S7eRM5c%3D; Path=/itim;
Secure; HttpOnly,Set-Cookie=com.ibm.isim.maxInactive=1800; Path=/itim; Secure,Strict-
Transport-Security=max-age=31536000; includeSubdomains,Strict-Transport-Security=max-
age=31536000; includeSubdomains,Transfer-Encoding=chunked,X-FRAME-OPTIONS=SAMEORIGIN]]
You probably want to do something like this, so you can process the JSON response (unless you already have JSON serialization/de-serialization for a POJO set up elsewhere).
JsonNode body = resp4.bodyToMono( JsonNode.class ).block();
You could do something simple like this to test.
System.out.println( resp4.bodyToMono( String.class ).block() );
Take a look at the documentation for ClientResponse and Mono<T> for more details.
Use response.getBody() function or simply response.body if you’re using any frontend framework.
I need to get some respones from some URL.
For this purpose I use http://unirest.io/java.html and Java.
Map<String, String> map = new HashMap<>();
map.put(key1, value1);
...
map.put(keyN, valueN);
String authToken = "{token}";
HttpResponse<String> response = Unirest.post(url)
.header("Authorization","Bearer " + authToken)
.header("Content-Type", "application/json")
.fields(map)
.asString();
As a result I receive response.getStatus() = 302 and some unexpected body.
At the same time I use Postman software to get the same responses. The settings are the following:
POST: url
Authorization: Type -> Bearer Token; Token = {{authToken}} // get the value from the previous request
Header :
"Authorization" : "Bearer " + {{authToken}}
Content-Type: application/json
Body:
{
key1 : value1,
...
keyN : valueN
}
And I get some expected response.
What makes the difference?
A 302 is a redirect response. Is it possible Postman is following the redirect and returning the resultant page? Take a look at the Location header in the response you get in Java, and see if following that gives you the same results you're seeing in Postman.
I'm struggling to push notifications to Android devices.
Here is a small piece of code I wrote:
String API_KEY = "AIzaSy....";
String url = "https://android.googleapis.com/gcm/send";
String to = "ce0kUrW...";
String data = "{\"to\": \"" + to + "\"}";
RequestBody body = RequestBody.create(MediaType.parse("application/json"), data);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).post(body).addHeader("Authorization", "key=" + API_KEY).build();
Response response = client.newCall(request).execute();
System.out.println(response.headers());
System.out.println(response.body().string());
Looking at https://developers.google.com/cloud-messaging/http#send-to-sync, it works fine when I try the send-to-sync option. I get a notification sound on my phone, but there is no actual notification, since there is no message or data linked to the push.
Now when I replace my data String with the following line, I still get the same result:
String data = "{ \"notification\": {\"title\": \"Test title\", \"text\": \"Hi, this is a test\"},\"to\" : \""
+ to + "\"}";
I'm not sure what I'm missing. My guess is that my format of the notification is wrong, but I've tried every combination that I've found so far during my research.
They writes to the log looks like this:
Content-Type: application/json; charset=UTF-8
Date: Thu, 21 Apr 2016 10:51:23 GMT
Expires: Thu, 21 Apr 2016 10:51:23 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alternate-Protocol: 443:quic
Alt-Svc: quic=":443"; ma=2592000; v="32,31,30,29,28,27,26,25"
Transfer-Encoding: chunked
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1461235877551
OkHttp-Received-Millis: 1461235877855
{"multicast_id":6596853786874127657,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1461235883968556%6ff215a7f9fd7ecd"}]}
The log entry indicates that your message was processed successfully. However for the notification with payload option you should send a JSON message like this:
{
"to" : "<your-recipient-id>",
"notification" : {
"body" : "Hi, this is a test",
"title" : "My test"
}
}
Please change as suggested and let us know if this helps.
You can check the Messaging Concepts and Options on Developer Guides - the guide provides some useful examples.
Maybe as an example - this is how you can handle the notifications.
In your app's onMessageReceived() you process it by retrieving the notification payload using notification as a key. For example:
public void onMessageReceived(String from, Bundle data) {
String notificationJSONString = data.getString("notification");
//then you can parse the notificationJSONString into a JSON object
JSONObject notificationJSON = new JSONObject(notificationJSONString );
String body = notificationJSON.getString("body");
Log.d(TAG, "Notification Message is : " + body);
}
Using Jersey 2.19, How do I get a CSRF token from a server which uses Spring Security 3 and make a successful login? I have two projects, a client which uses REST, and a server which was created using JHipster.
First, I'm making a get request to http://localhost:8080 and I'm getting this response headers:
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Language:en
Content-Length:17229
Content-Type:text/html;charset=utf-8
Date:Tue, 21 Jul 2015 19:24:40 GMT
Expires:0
Last-Modified:Thu, 02 Jul 2015 17:07:31 GMT
Pragma:no-cache
Server:Apache-Coyote/1.1
Set-Cookie:CSRF-TOKEN=0902449b-bac7-43e8-bf24-9ec2c1faa48b; Path=/
X-Application-Context:application:dev:8081
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
I extract the Set-Cookie header and I get the CSRF token from there. Then I'm making a post request this way:
http://localhost:8080/api/authentication?j_username=user&j_password=user&submit=Login
With this request headers:
Content-Type: application/x-www-form-urlencoded
X-CSRF-TOKEN: <extracted token>
Using Chrome's plugin postman, I can make a correct post request for login, but with Jersey, I'm unable to send correctly the CSRF token (I get 403 response).
This is the response:
{"timestamp":1437507680089,"status":403,"error":"Forbidden","message":"Expected CSRF token not found. Has your session expired?","path":"/api/authentication"}
This is the jersey code:
WebTarget hostTarget = getClient().target("http://localhost:8080");
Response r = hostTarget.request().get();
String header = r.getHeaderString("Set-Cookie");
String csrf = null;
List<HttpCookie> cookies = HttpCookie.parse(header);
for (HttpCookie c : cookies) {
if("CSRF-TOKEN".equals(c.getName())){
csrf = c.getValue();
break;
}
}
WebTarget loginTarget = hostTarget.path("/api/authentication");
loginTarget = loginTarget.queryParam("j_username", username)
.queryParam("j_password", password)
.queryParam("submit", "Login");
Builder req = loginTarget.request(MediaType.APPLICATION_JSON_TYPE);
if (csrf != null) {
req = req.header("X-CSRF-TOKEN", csrf);
}
Response cr = req.post(Entity.entity(null,
MediaType.APPLICATION_FORM_URLENCODED_TYPE));
System.out.println("Response: " + cr.readEntity(String.class));
Thanks for your time.
After much trial and error, I found the solution. Is important to take in count cookies (as indicated by Roman Vottner) for REST configuration to communicate with spring security. The important cookie that must be present is JSESSIONID and the header X-CSRF-TOKEN (or whatever header name is configured in the server), so capture them in a initial request and send them again.
I've decided to send all the cookies to the server in this way.
WebTarget hostTarget = getClient().target("http://localhost:8080");
Response r = hostTarget.request().get();
String headerCookies = r.getHeaderString("Set-Cookie");
Map<String, NewCookie> cookies = r.getCookies();
String csrf = cookies.get("CSRF-TOKEN").getValue();
WebTarget loginTarget = hostTarget.path("/api/authentication");
loginTarget = loginTarget.queryParam("j_username", username)
.queryParam("j_password", password)
.queryParam("submit", "Login");
Builder req = loginTarget.request(MediaType.APPLICATION_JSON_TYPE);
req = req.header("Cookie", headerCookies);
if (csrf != null) {
req = req.header("X-CSRF-TOKEN", csrf);
}
Response cr = req.post(Entity.entity(null,
MediaType.APPLICATION_FORM_URLENCODED_TYPE));
//The response is empty (in my case) with status code 200
System.out.println("Response: " + cr.readEntity(String.class));
I'll lay down my code first: Note: I also have log output at the bottom of the question.
Server Side:
#Post
#Consumes("application/octet-stream")
public Representation post(InputStream zip, #HeaderParam(value = "Content-Disposition") HttpHeaders headers) throws Throwable {
System.out.println(headers); //Prints null - want the header to not be null here
String uploadedFileLocation = getStartingDir() + "/" + "abc.zip";
writeToFile(zip, uploadedFileLocation);
return new StringRepresentation("Uploaded!");
}
Client Side:
public static void main(String[] args) throws Exception {
final String BASE_URI = "http://localhost:8080/server/upload";
Client client = Client.create();
WebResource service = client.resource(BASE_URI);
client.setChunkedEncodingSize(1024);
client.addFilter(new LoggingFilter());
File zip = new File("C:/Users/sdery/Desktop/abc.zip");
InputStream fileInStream = new FileInputStream(zip);
String sContentDisposition = "attachment; filename=\"" + zip.getName()+"\"";
ClientResponse response = service.header("Authorization", "Basic xxx=").header("Content-Disposition", (Object)sContentDisposition).type(MediaType.APPLICATION_OCTET_STREAM).post(ClientResponse.class, fileInStream);
System.out.println("Response Status : " + response.getEntity(String.class));
}
First off, the file transfer works, I'm happy. However, I would like to get the headers on the server side so I don't have to hard code the file name. Any ideas as to why it is comin' up null? Does it have to do with me using ClientResponse instead of ClientRequest?
Jul 31, 2013 8:44:12 AM com.sun.jersey.api.client.filter.LoggingFilter log
INFO: 1 * Client out-bound request
1 > POST http://localhost:8080/server/upload
1 > Content-Disposition: attachment; filename="abc.zip"
1 > Authorization: Basic xxx=
1 > Content-Type: application/octet-stream
(zip bytes)
INFO: 1 * Client in-bound response
1 < 200
1 < Date: Wed, 31 Jul 2013 12:44:12 GMT
1 < Date: Wed, 31 Jul 2013 12:44:12 GMT
1 < Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
1 < Content-Length: 88
1 < Set-Cookie: rememberMe=deleteMe; Path=/server; Max-Age=0; Expires=Tue, 30-Jul-2013 12:44:12 GMT
1 < Content-Type: text/plain; charset=UTF-8
1 < Accept-Ranges: bytes
1 < Server: Restlet-Framework/2.0.4
1 < Real-Token: bar
1 <
Uploaded!
From the log output, it seems that the header containing Content-Disposition is there. Does this mean I should be able to retrieve the value from the server side code?
You're parameter is of the wrong type. You should declare the parameter as a String. HttpHeaders is for getting all the headers and is annotated with a #Context. #HttpParam can only be converted to a limited number of types.
From the Jersey documentation for HeaderParam.
Binds the value(s) of a HTTP header to a resource method parameter, resource class field, or resource class bean property. A default value can be specified using the DefaultValue annotation. The type T of the annotated parameter, field or property must either:
Be a primitive type
Have a constructor that accepts a single String argument
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.
So you're code would be more like
#Post
#Consumes("application/octet-stream")
public Representation post(InputStream zip, #HeaderParam(value = "Content- Disposition") String contentDisposition) throws Throwable {
System.out.println(contentDisposition);
String uploadedFileLocation = getStartingDir() + "/" + "abc.zip";
writeToFile(zip, uploadedFileLocation);
return new StringRepresentation("Uploaded!");
}
First off, I apologize that my solution is from a JavaScript/PHP reference and not Java, but I believe your solution may be similar.
Add a new header named 'X-FILENAME' and set the name of your file as the header data. I believe your code would look something like this:
ClientResponse response = service.header("X-FILENAME", "abc.zip");
Then, on your server, you should be able to retrieve that header param (In PHP it is the $_SERVER global, it looks like in yours it may be #HeaderParam).
Also, for reference just in case this applies to you, in PHP when you retrieve the header param you need to use a modified param name by adding 'HTTP_' to the front and changing all dashes to underscores like this 'HTTP_X_FILENAME'. So on the client you sent 'X-FILENAME' while on the server you retrieve that same value with 'HTTP_X_FILENAME'.
I hope this leads you in the right direction.