Is it possible to store an object in HttpHeaders in Java? - java

Forgive my ignorance - a jr developer here. I'm trying to make a PUT call to a client API. In the documentation it shows the request headers have an object in them. I thought headers could only have a String value. How can I add an object to my HttpHeaders object?
Request Model from API Documentation
requestHeader {
"headerA": "valueA",
"headerB": {
"headerB1": "valueB1",
"headerB2": "valueB2"
},
"headerC": "valueC"
}
requestBody {
"object": {
"variable1": 12345,
"variable2": 54321
},
"sameNums": false }
I'm using HttpHeaders from package org.springframework.http - the set() and add() methods take Strings as parameters. How can I add an object as a header value?

Related

Problems Sending FormUrlEncoded using Retrofit

I have this request and I need to send it by FormUrlEncoded using Retrofit
{
"clnt_id": "OQW",
"clnt_res": "AA!##$T",
"type": "SCDS",
"len": "ASD"
}
I used this code:
#FormUrlEncoded
#POST("Endpoint")
#Headers("Accept: Application/JSON")
fun connect(
#Field("clnt_id") clnt_id: String,
#Field(value = "clnt_res", encoded = false) clnt_res: String,
#Field("type") type: String,
#Field("len") len: String
): Observable<Token>
First, thing is that the request is not sent as JSON
Second, the value of "clnt_res", encoded by retrofit
You have 2 options to send json request from android using Retrofit.
Create Pojo Model of json request and pass it by setting values of it.
Create HashMap and pass it to request.
Here is solution using 2nd Method:
Create hashmap and put key(parameters) and value:
Map<String,String> requestMap = new HashMap<>();
requestMap.put("clnt_id","your_value");
requestMap.put("clnt_res","your_value");
requestMap.put("type","your_value");
requestMap.put("len","your_value");
Then pass it to your retrofit request using FieldMap:
#FormUrlEncoded
#POST("Endpoint")
#Headers("Accept: Application/JSON")
fun connect(
#FieldMap requestMap:Map<String,String>
): Observable<Token>
I finally get the answer and it was a problem with symbol '$' in 'clnt_res' value "AA!##$T", The problem is in kotlin to escape a special char you need to do this "\$", what I made the IDE didn't tell me that it is wrong is this "$/".

Unable to pass Array from Angular 2 typescript to Spring Java

I am trying to pass a String array from my typescript
tmp : Array<string> = [];
So I have a function which takes in this array as a parameter input
passValues(test : Array<string>) {
........
// some method to call post method from service
}
So in service
public passingOfValues( test : Array<string> ) : Observable<Array<string>> {
let headers = new Headers({ 'Content-Type': 'application/json'} );
let options = new RequestOptions({ headers: headers);
let response = this.http.post(this.basePath + this.modulePath + '/getArrayValue', {'test' : test }, options)
.map(this.extractData)
.catch(this.handleError);
return response;
}
But I am getting errors such as System property [org.owasp.esapi.devteam] is not set
And I read on other posts that I have to stringify the array before passing to backend.
Is there a reason why I need to stringify / also can I just pass the raw array?
EDIT 1 :
including backend controller codes
public ResponseEntity<?> getArrayValues( ArrayList<String> test ) {
logger.debug("### Test if array has a size ###" + test.size());
}
Apparently size already shows 0 from here.
EDIT 2 :
While debugging, i realised that the SQL at the back is receiving
say
HOME CHARACTER(20 OCTETS)
does this make any difference?
Like passing of string into octets or do I have to do some conversion?
Sorry if I have alot of questions am also working hard on debugging and learning more about it!
Most of the developers like JSON data as request and it's good practice in RESTful apis. why?
JSON format is {key1: value1, key2: value 2,....}
You are passing
this.http.post(this.basePath + this.modulePath + '/getArrayValue',{'test' : YOUR_ACTUAL_ARRAY})
form the front-end. The httpClient.post(url,body,options?) has url and body as mandatory. How can you get it in back-end? Since you have body only,
public ResponseEntity<?> getArrayValues(#RequestBody List<String> test) {
// codes
}
Key of passed parameter from front-end test and variable which
listens in back-end should be in same name. Otherwise
#RequestBody("KEY_NAME") List<String> any_variable
As you asked from comment, you may have two key value pairs. Eg : { "test" : value1, "tmp": value2}. Assume value1 and value2 both are String array.
this.http.post(this.basePath + this.modulePath + '/getArrayValue',{'myJson' : YOUR_JSON})
There are lot of way(Eg : Gson,ObjectMapper etc). I use another way.
Create a class called TestTmpConverter
class TestTmpConverter{
List<String> test;
List<String> tmp;
//No-argument constructors & Argument constructors
//Getters
}
In controller
public ResponseEntity<?> getArrayValues(#RequestBody List<TestTmpConverter> myJson ) {
List<TestTmpConverter> test=myJson.getTest();
List<TestTmpConverter> tmp=myJson.getTmp();
// Do your work
}
I only showed one way.There are a lot of way to pass data to back-end like #RequestParam, #PathVariable etc. I feel now you get something how you can pass the data.
For your client put your data directly on POST's body:
public passingOfValues( test : Array<string> ) : Observable<Array<string>> {
let headers = new Headers({ 'Content-Type': 'application/json'} );
let options = new RequestOptions({ headers: headers);
let response = this.http.post(this.basePath + this.modulePath + '/getArrayValue',
test, options)
.map(this.extractData)
.catch(this.handleError);
return response;
}
On your REST service use the #RequestBody annotation:
public ResponseEntity<?> getArrayValues(#RequestBody String[] test ) {
logger.debug("### Test if array has a size ###" + test.size());
}

Lagom Send custom header

I'm working on Lagom POC on sending POST request to Non lagom service with custom Header. In my case I'm trying to hit postman-echo to test the custom header.
However, it looks the headers are not set though I made code changes accordingly:
public CompletionStage<DsapAuthorizationResponse> hitAPI(AuthorizationRequest request) {
DsapWSRequest dsapWSRequest = new DsapWSRequest();
dsapWSRequest.username = request.username;
dsapWSRequest.password = request.password;
CompletionStage<DsapAuthorizationResponse> dsapresponse = dsapExternalService
.authenticate()
.handleRequestHeader(requestHeader -> {
requestHeader.withHeader("Authorization","Basic mncndsjna");
System.out.println("My Headers>>>>>>>> " + requestHeader);
return requestHeader;
})
.handleResponseHeader((responseHeader,b) -> {
System.out.println("RESPonse Header >>>>>>> : "+responseHeader);
return b;
})
.invoke(dsapWSRequest);
return dsapresponse;
}
In the above code header authorization is not set in the request. I am not getting this header in the echo which is mapped correctly in my POJO.
here is the complete code from my GitHub
https://github.com/sourabhsar/Lagom-Unmanaged-Service-Demo/tree/poc/lagom-request-response
I followed the steps mentioned here:
https://groups.google.com/forum/#!topic/lagom-framework/yvKmqvtZWFs
and also followed few other blogs/articles.
However so far I haven't found any blog which they are sending request to unmanaged external service with custom header. I'm not sure whats wrong in my code.
requestHeader.withHeader returns a new object with the added header, but the code you have written returns the original requestHeader object. In general, many Lagom APIs follow a principle of using immutable objects, with methods that return a new, modified instance, rather than changing the instance the method is called on.
Try this:
.handleRequestHeader(requestHeader -> {
RequestHeader modifiedRequestHeader =
requestHeader.withHeader("Authorization","Basic mncndsjna");
System.out.println("My Headers>>>>>>>> " + modifiedRequestHeader);
return modifiedRequestHeader;
})

Issue in passing string in Request Body

I am facing an issue while making a request body to do an API call in Java.
Required Body
{
"id" : [1,2]
}
I have an integer array with me lets say arr, I am creating the request something like:-
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",Arrays.toString(arr));
String stringBody = jsonObject.toJSONString();
RequestSpecification specification = RestAssured.with();
specification.body(stringBody);
Response response = specification.post(endpoint);
What it actually does is make the request body as something like below.
{
"id" : "[1,2]"
}
As it sends the value as String so my server throws an error, Expected a list of items but got type \"unicode\".
Can somebody help me in here. How do I send it in raw format instead of String.
Use
jsonObject.put("id",Arrays.asList(arr));
to build the json body.

In Java, how to set the header of a Restlet Response?

I can't seem to figure out how to add headers to my restlet response. When I look at the available methods in the Response object, all I see is setStatus, setEntity, and setAttributes but none of these tell me how to set custom http headers on the response.
For example, I have a GET call the returns something like the following:
HTTP/1.1 200 OK
Content-Type: text/json
Content-Length: 123
Some-Header: the value
Some-Other-Header: another value
{
id: 111,
value: "some value this could be anything",
diagnosis: {
start: 12552255,
end: 12552261,
key: "ABC123E11",
source: "S1",
}
}
Whatever it maybe. In the handleGet method, I handle it like so:
final MediaType textJsonType = new MediaType("text/json");
#Override
public void handleGet() {
log.debug("Handling GET...");
final Response res = this.getResponse();
try {
final MyObject doc = this.getObj("hello", 1, "ABC123E11", "S1");
final String docStr = doc.toString();
res.setStatus(Status.SUCCESS_OK);
res.setEntity(docStr, textJsonType);
// need to set Some-header, and Some-other-header here!
}
catch(Throwable t) {
res.setStatus(Status.SERVER_ERROR_INTERNAL);
res.setEntity(new TextRepresentation(t.toString()));
}
}
Because Restlet is more about the REST architectural principles than HTTP, it tries to be protocol agnostic and doesn't expose the HTTP headers directly. However, they are stored in the org.restlet.http.headers attribute of the response (as a Form). Note that you can only set custom headers this way, not standard ones (these are handled directly by the framework, e.g. Content-Type depends on the Representation's MediaType).
See this for an example:
http://blog.arc90.com/2008/09/15/custom-http-response-headers-with-restlet/ (link content also available from the Internet Archive Wayback Machine).

Categories

Resources