ApacheCamel - How to get HttpRequest and HttpReponse from exchange after HttpCopoment - apache-camel

How to get HttpRequest and HttpReponse from exchange after HttpCopoment?
Any hints or ideas are more than welcome
Below is the code example
from("direct:restendpoint").routeId("direct_restendpoint")
.to("https://<URL_SERVICE>")
.process(exchange -> {
String responseCode = exchange.getIn().getHeader("CamelHttpResponseCode").toString();
//How to get httpRequest and httpResponse here?
})

Related

How to do post request to external api using rest template?

While I am executing this i getting an error like this ("Content type 'text/plain;charset=UTF-8' not supported]"). Please help me to get this problem resolved.
public String saveCourse(CourseEntity courseDetails ) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<CourseEntity> entity = new HttpEntity<CourseEntity>(courseDetails,headers);
return restTemplate.exchange(
"http://localhost:8062/courses", HttpMethod.POST, entity, String.class).getBody();
}

A problem with getting response from Spring Boot after a fetch request

I have a very annoying issue. I have this Javascript code inside a React component:
let entityJson = JSON.stringify(entityObject);
fetch("http://localhost:8080/add", {
method: "POST",
mode: "no-cors",
headers: { "Content-Type" : "application/json charset=UTF-8"},
body: entityJson
}).then(data => console.log(data));
This is sending a request to the follow function in an Spring Boot Rest controller:
#PostMapping(produces = "application/json")
public AddEntityResponse newEntity(#RequestBody String person, HttpServletResponse response) {
AddEntityResponse respons = new AddEntityResponse(0,0);
Gson jsonReader = new Gson();
try{
Person newPerson = jsonReader.fromJson(person, Person.class);
personStore.addPerson(newPerson);
respons.setStatus(1);
respons.setId(newPerson.getId());
}catch(Exception e){
System.out.println(e.toString());
}
return respons;
}
But regardless of what I add, this is the request I am getting an empty response, so I guess the issue is in the Java code. I am learning this stuff now, started today so sorry if this seem a bit stupd.

For 400 bad request in cxfrs:rsclient in camel, the exchange is null. For 200 http status, the exchange object is set

Below is the code snippet to consume an api endpoint. For 200 http response, the exchange object contains the payload received. But for 400 response, the payload received is not set in exchange object. Is anything missing in the code below?
Exchange exchange = serviceProducer.send(endPoint, new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.setPattern(ExchangePattern.InOut);
Message inMessage = exchange.getIn();
inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
inMessage.setHeader(Exchange.CONTENT_TYPE, "application/json");
inMessage.setHeader(Exchange.HTTP_METHOD, "POST");
inMessage.setHeader(Exchange.HTTP_QUERY, "clientId=" + ClientId);
inMessage.setBody(request);
inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, SearchResponse.class);
inMessage.setHeader(Exchange.CONTENT_TYPE, "application/json");
}
});
SearchResponse searchResponse = (SearchResponse) exchange.getOut().getBody();
getOut() creates a blank output message. You need to use getIn() or getMessage().
SearchResponse searchResponse = (SearchResponse) exchange.getIn().getBody();
https://camel.apache.org/manual/latest/faq/using-getin-or-getout-methods-on-exchange.html#UsinggetInorgetOutmethodsonExchange-UsinggetInorgetOutmethodsonExchange

Azure B2C - 401 unauthorised trying to read id_token in code after logging in

I am trying to use the token granted by a secured AAD domain when using my web app
I followed the advice on this link: Retrieve Access Token within a AAD secured Azure Web App
I have managed to get as far as logging in and verifying the ./me URL correctly shows me my token
However when I try and call same token in code I get 401 unauthorised
I have been using the Resource Explorer to configure the additionalLoginParams and have tried to put the app ID as well as the graph URL but nothing has solved the problem
async public Task<string> GetToken()
{
HttpClient _client = new HttpClient();
string _token = "";
HttpResponseMessage response = await _client.GetAsync("https://alfreton.azurewebsites.net/.auth/me");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
ReadUserToken readUserToken = new ReadUserToken();
readUserToken = JsonConvert.DeserializeObject<ReadUserToken>(responseBody);
_token = readUserToken.id_token;
return _token;
}
}
}
EDIT Following the advice below the code now looks like this but I am still getting an Unauthorized error messsage
async public Task<string> GetToken()
{
HttpClient _client = new HttpClient();
string _token = "";
string accessToken = this.Request.Headers["X-MS-TOKEN-AAD-ACCESS-TOKEN"];
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await _client.GetAsync("https://alfreton.azurewebsites.net/.auth/me");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
ReadUserToken readUserToken = new ReadUserToken();
readUserToken = JsonConvert.DeserializeObject<ReadUserToken>(responseBody);
_token = readUserToken.id_token;
return _token;
}
When I read through the headers, I find there is X-MS-TOKEN-AAD-ID-TOKEN - can I use that to get an access token?
I agree with #juunas, the URL expects the authentication cookie to be passed in the request when you aceess ./me URL.
The provider-specific tokens are injected into the request header, so you can easily access them. Your provider is AAD, so it should be
string accessToken = this.Request.Headers["X-MS-TOKEN-AAD-ACCESS-TOKEN"];
OK I figured it out, what I needed to do is get X-MS-TOKEN-AAD-ID-TOKEN from the Request Headers after logging in then pass that in as the Bearer and that in turn got me a X-MS-TOKEN-AAD-ACCESS-TOKEN which I can use for accessing the API
Thanks loads!

DART & GAE : Why a POST method send from dart can't be evaluate in GAE?

I have a Dart code used to send an HttpRequest with a POST method to my GAE WepApp2 application. The dart code is executed in chromium and serve by Chrome dev editor. I add in my GAE code some headers to avoid the XHR error in the client side.
The dart code send the datas to my GAE app but I can't read the data with self.request.POST.get("language")) and the app never enter in def post(self): section but with self.request.body I can read the data.
Could you explain that and provide some correction to have a full POST compliant code?
dart:
void _saveData() {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText);
}
});
// POST the data to the server
var url = "http://127.0.0.1:8080/savedata";
request.open("POST", url, async: false);
String jsonData = JSON.encode({"language":"dart"});
request.send(jsonData);
}
GAE code in my handler:
def savedata(self):
logging.info("test")
logging.info(self.request.body)
logging.info(self.request.POST.get("language"))
def post(self):
logging.info("test 2")
logging.info(self.request.POST.get("language"))
self.response.headers["Access-Control-Allow-Origin"] = "http://127.0.0.1:49981"
self.response.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
In Dart, if you don't specify request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") in your HttpRequest, the data is considered by GAE like a bite stream and you can only read them with self.request.body
If you add the Content-Type header in Dart you need also to change the data formating. In my case I mimic a form sending with POST method so I change String jsonData = JSON.encode({"language":"dart"}); by String jsonData = "language=dart2";
IN GAE python I can now read the data with self.request.POST.get("language")
If you need to send a JSON from DART to GAE, you can encode the string like this:
String jsonData = JSON.encode({"test":"valuetest1"});
String datas = "datas=$jsonData";
request.send(datas);
In GAE you can read the datas like this:
my_json = json.loads(self.request.POST.get("datas"))
logging.info(my_json["test"])
The complete code:
Dart
void _saveData2() {
String url = "http://127.0.0.1:8080/savedata";
HttpRequest request = new HttpRequest()
..open("POST", url, async: true)
..setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
..responseType = "arraybuffer";
String jsonData = JSON.encode({"test":"valuetest1"});
String datas = "datas=$jsonData";
request.send(datas);
}
GAE
class PageHandler(webapp2.RequestHandler):
def savedata(self):
self.response.headers.add_header('Access-Control-Allow-Origin', '*')
self.response.headers['Content-Type'] = 'application/json'
#logging.info(self.request)
my_json = json.loads(self.request.POST.get("datas"))
logging.info(my_json["test"])

Resources