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.
Related
I'm using rest assured to send a post with a generated body from a model class. The model class uses the builder pattern and I confirmed that it is getting built correctly:
Request body:
McpSalesInvoicesPost(invoices=[McpSalesInvoices(type=PRE_ORDER, amount=212.0, currencyCode=INR, transactionDate=2020-10-24T22:43:24, payments=[McpSalesPayments(type=CASH, amount=212.0, currencyCode=INR, reference=reference text sample 376, transactionDate=2014-08-20T19:23:51)])])
When I use that object in the rest assured post call I get an empty body in the request. Here is the rest assured code:
response = SerenityRest
.given()
.filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
.contentType(ContentType.JSON)
.header(new Header("x-openapi-clientid", "client-id-1"))
.body(requestBody)
.when()
.request(verb, SALES_BASE_URL + endpoint);
where request body is the built object mentioned above and this gives:
Body:
{
}
for the request. Any ideas on where I'm going wrong?
A
Maybe try .with().body(object).
response = SerenityRest
.given()
.filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
.contentType(ContentType.JSON)
.header(new Header("x-openapi-clientid", "client-id-1")).with().
.body(requestBody)
.when()
.request(verb, SALES_BASE_URL + endpoint);
I'm using Katalon Studio and using it to send an API request. The request is basically returning information I want to use in the HTTP Header. I can use Groovy or Java to extract this but not sure how I can do it.
I've tried create_game_response.getHeadewrFields(GameCode) in order to get the GameCode but it won't work.
Here is the code I use
WS.sendRequest(findTestObject('UserRestService/Create Game'))
WS.verifyResponseStatusCode(create_game_response, 201)
def header_text = create_game_response.getHeaderFields()
println(header_text)
def game_code = create_game_response.getHeaderFields();
String game_code_list = game_code.toString()
println(game_code_list)
And this is the response:
{GameCode=[1jwoz2qy0js], Transfer-Encoding=[chunked], null=[HTTP/1.1 201 Created]}
I'm trying to extract "1jwoz2qy0js" from the game code and use it as a string, how can I do this?
getHeaderFields() returns a Map of the headers where each header is a List. Rather than converting that to a String and attempting to parse it, just get the field you want:
Map headers = create_game_response.getHeaderFields()
List gameCodes = headers["GameCode"]
And then select the first one, if that's all there is:
assert gamesCodes[0] == "1jwoz2qy0js"
Groovy code below:
str = '{GameCode=[1jwoz2qy0js], Transfer-Encoding=[chunked], null=[HTTP/1.1 201 Created]}'
left_idx = str.indexOf('[') + 1
right_idx = str.indexOf(']')
print str.substring(left_idx,right_idx)
Output:
1jwoz2qy0js
I've been trying to place labels over newly created nodes using Neo4J restful api. The following is the CURL request I've tried.
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7474/db/data/");
String propertyUri_labels = "http://localhost:7474/db/data/node/9/labels";
Response response = target
.path(propertyUri_labels)
.request(MediaType.APPLICATION_JSON)
.header("application/xml", "true")
.accept(MediaType.APPLICATION_JSON)
.put(Entity.entity("\"" + "Artist" + "\"", MediaType.APPLICATION_JSON_TYPE));
System.out.println( String.format( "PUT to [%s], status code [%d]",
propertyUri_labels, response.getStatus() ) );
However, I have not been successful and got an status code [400]. Is there something wrong with my URL "http://localhost:7474/db/data/node/9/labels" ?
Pls help.
Thanks!
Try a POST instead of PUT.
Check the documentation => http://neo4j.com/docs/rest-docs/current/#rest-api-node-labels
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());
}
}
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.