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

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();
}

Related

401 When passing the token using graphic onenote api

I am new to Microsoft graph so this might be a dumb question.
So I am writing a command line application trying to update a page in our team onenote. (enterprise onenote)
Here is the code I got work getting the token.
https://login.microsoftonline.com/common/oauth2/authorize?client_id=my_client_Id&response_type=code&redirect_uri=Some_uri&resource=https://graph.microsoft.com&scope=Notes.ReadWrite.All
I got the token as strCode and trying to retrieve all the notes under this account by these codes:
var baseAddress = new Uri("https://graph.microsoft.com/v1.0/me/onenote");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
var request = new HttpRequestMessage(HttpMethod.Get, #"/pages");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", strCode);
using (var response = httpClient.SendAsync(request).Result)
{
string responseData = response.Content.ReadAsStringAsync().Result;
}
}
And in the response data I got
"{ \"error\": { \"code\": \"InvalidAuthenticationToken\", \"message\": \"CompactToken parsing failed with error code: -2147184105\", \"innerError\": { \"request-id\": \"*********************", \"date\": \"2017-06-08T18:25:06\" } } }"
Any idea how to fix this..?
Problem resolved .
I need to convert the authentication code into a "real" access token..
The one that I got is not an access token.

Json Web Token - jose4j - SyntaxError: Unexpected token e in JSON at position 0

I have a controller which tries to get a token.
I got this error in postman when I execute it in the view PRETTY
Unexpected 'e'
But if I go to the view RAW I can see the token like this.
eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJpc3MiOiJJc3N1ZXIiLCJhdWQiOiJBdWRpZW5jZSIsImV4cCI6MTQ3NTQ1OTMyNiwianRpIjoiTmF3d000bDVGRmFRZ0dBQkwzS3N5USIsImlhdCI6MTQ3NTQ1ODcyNiwibmJmIjoxNDc1NDU4NjA2LCJzdWIiOiJzdWJqZWN0IiwiZW1haWwiOiJtYWlsQGV4YW1wbGUuY29tIn0.f97SFDaAjUyUDK_UQgwgnCTewd0yw6tWK6DFLzpALFq177f1QMTYPbVdiIG1ViJ0FNJ6fUCleCd8BmrToUn25VSmRv799dtcz-xaN1kOgw90NQ00kPUhnDXG01-7hImkHfbmZZWORukP2yPK1sHWzpdjg9fJOvRZpZ6ZWli4HeuYRJqsFOv7PvwmGH9JnfRTf_2tboL-oAYBpT367eh60TggrvMgmrO_Taj5M7qGG0GpbwuVh_HTAkaKv7T2WmuZ2JPANhe5JvY_DDaqChtwd0IPREAhK3Xr-nTOIuwbQ0Y1hhOGfvDmikQj6DXnCERYixP6eR1dhC8n3bKvXyaVmA
This is the code of my controller.
#Path("/demo")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response testMethod() throws JSONException, IOException {
RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
rsaJsonWebKey.setKeyId("k1");
JwtClaims claims = new JwtClaims();
claims.setIssuer("Issuer");
claims.setAudience("Audience");
claims.setExpirationTimeMinutesInTheFuture(10);
claims.setGeneratedJwtId();
claims.setIssuedAtToNow();
claims.setNotBeforeMinutesInThePast(2);
claims.setSubject("subject");
claims.setClaim("email","mail#example.com");
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(rsaJsonWebKey.getPrivateKey());
jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
String jwt = jws.getCompactSerialization();
if(jwt == null){
return Response.status(204).entity(jwt).build();
}
return Response.status(200).entity(jwt).build();
}
I ignore the error in postman but I get the same error when try to execute it in Chrome.
I try to call my RESTful controller with angular like this, but I always get into the onError method with the message within the response parameter.
angular.min.js:118 SyntaxError: Unexpected token e in JSON at position 0
This is the code in angular
app.service('TokenService', function($http){
this.getToken = function(){
function onSuccess(response){
console.log('got it');
}
function onError(response){
console.log('fail');
}
return $http({
method : 'GET',
url : 'http:localhost:8080/rest/demo',
header: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
}
}
My reference of the code for the token is from here with Jose4j
UPDATE
I solved this. I still think the way I did it initially it should work also, but I don't still understand why I get the error.
I created a pojo named Token with a property token as String then I changed this
return Response.status(200).entity(jwt).build();
to this:
Token token = new Token();
token.setToken(jwt);
return Response.status(200).entity(token).build();
This is my workaround to return a real json object.
I know it's much too late now, but I've faced the same problem and got it fixed with your solution, so Thanks.
Just for the sake of whoever came across this issue later. In my case I do it like this.
HashMap<String, String> credential = new HashMap<>();
credential.put("token", jwtToken);
apiResp = ResponseEntity.ok(jwtToken);
Btw, I also seem to figured out the problem which is Angular might expect that response from server is JSON object by default then parse it to JavaScript object for us.
So we got our error because we return string as a response entity and it can't parse string to an object. That's why putting the token in POJO solved it.
The other way around is setting return type from client-side like this.
login(username: string, password: string): Observable<any> {
let body = {username, password};
let res = this.http.post(
`${API.AUTHENTICATION}`, body, {
responseType: 'text'
});
return res;
}
Now, JS will know that the response is of string type and it won't try to parse it to an object anymore.

angularjs sending request front to back-end

i am sending remove request from front-end using angularjs code for js is
var data = ersutils.getJsonCopy({"id" : $scope.resourceList[idx].id},$scope.resourceList[idx]);
ResourceService.remove(data, function(data){
//vm.dtInstance.reloadData(undefined, false);
$modalInstance.close();
}, function (resp){
if(resp.status == 500){
scope.modalinfo.message = "<code> this resource has booking(s) do you want to delete? </code>";
ResourceService.remove({'id': delRes}, function(){
//vm.dtInstance.reloadData(undefined, false);
$modalInstance.close();
})
}else{
scope.modalinfo.message = "<code> Unable to delete this Resource </code>";
}
});
here ersutils provide jsoncopy for multiple parameters...when i have sent this data to rest api it says that unsupported media type
restapi code for delete is
#DELETE
#Path("/{id:\\d+}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response removeRes(#PathParam("id") int id,Map<String, Object> source){
Map<String, Object> resp = new HashMap<>();
//Map<String, Object> source=new HashMap<>();
try{
resp.put("response",service.removeRes(id,source));
return Response.status(Status.OK).entity(resp).build();
}catch(FrontErsException e){
resp.put("cause", e.getMessages());
return Response.status(Status.CONFLICT).entity(resp).build();
}catch(ErsException e){
resp.put("cause", e.getMessages());
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(resp).build();
}
}
error is
angular.js:10514 DELETE http://localhost:8080/ers_dev/rest/resources/10?dynamicFields=%7B%22code%22…2016-05-27%22%7D&firstName=vinay&isHuman=true&name=N%2FA&typeName=Employee 415 (Unsupported Media Type)
Did you try using #Consumes(MediaType.APPLICATION_FORM_URLENCODED) instead of APPLICATION_JSON?
Don't know exactly what you're using for your backend, but uUsually DELETE requests doesn't care about request body, so params are URL encoded.

WPF and MVC4 Web API Internal Server Error 500 on POST

So I'm attempting to attach to a web api method via a WPF service, but get only a 500 error on anything other than a GET.
WPF call:
using (var client = new HttpClient())
{
var user = new MyUser
{
EntityID = Guid.NewGuid(),
FirstName = "WPF",
LastName = "test"
};
var formatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<MyUser>(user, formatter);
client.BaseAddress = new Uri("http://localhost:19527/api/");
var response = await client.PostAsJsonAsync("MyUser", content);
//.ContinueWith((postTask) => result = (postTask.Result.Content == null) ? "Could not create user" : "User created successully!");
var r = response.StatusCode;
}'
...and the receiving controller:
public HttpResponseMessage Get(string badgeId)
{
return Request.CreateResponse<bool>(HttpStatusCode.OK, (service.UserByBadge(badgeId) != null));
}
public HttpResponseMessage Put(MyUser user)
{
return Request.CreateResponse<bool>(HttpStatusCode.OK, service.UpsertUser(user));
}
public HttpResponseMessage Post(MyUser user)
{
if (service.UpsertUser(user)) return Request.CreateResponse<MyUser>(HttpStatusCode.OK, service.Get<MyUser>(u => u.BadgeID == user.BadgeID));
return Request.CreateResponse<MyUser>(HttpStatusCode.NoContent, null);
}'
The service on the WebApi controller is a GenericRepository, which is working fine, since the Get method returns as expected. It's only when I use Post that I get the error. Debugging the methods throws the break point in the Get, but not in the Post, so I don't think it's ever being called.
Here's the route config:
routes.MapRoute(
name: "Default",
url: "api/{controller}/{action}/{id}",
defaults: new { controller = "{controller}", action = "{action}", id = UrlParameter.Optional }
);
I've tried different examples from other SO posts, but none appear to address this issue specifically. I'm guessing there's something wrong with how I've constructed the Post() method?
================================================================
RESOLUTION: Model being passed was failing property validations. Why this was causing a 500, not certain. But once I solved for this, API method began working.
If anybody has a "why" explanation, would love to know for future reference.

Set parameters with HTTP POST in Apex

I'm trying to set POST content using Apex. The example below sets the variables using GET
PageReference newPage = Page.SOMEPAGE;
SOMEPAGE.getParameters().put('id', someID);
SOMEPAGE.getParameters().put('text', content);
Is there any way for me to set the HTTP type as POST?
Yes but you need to use HttpRequest class.
String endpoint = 'http://www.example.com/service';
String body = 'fname=firstname&lname=lastname&age=34';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setbody(body);
Http http = new Http();
HTTPResponse response = http.send(req);
For additional information refer to Salesforce documentation.
The following apex class example will allow you to set parameters in the query string for a post request -
#RestResource(urlmapping = '/sendComment/*')
global without sharing class postComment {
#HttpPost
global static void postComment(){
//create parameters
string commentTitle = RestContext.request.params.get('commentTitle');
string textBody = RestContext.request.params.get('textBody');
//equate the parameters with the respective fields of the new record
Comment__c thisComment = new Comment__c(
Title__c = commentTitle,
TextBody__c = textBody,
);
insert thisComment;
RestContext.response.responseBody = blob.valueOf('[{"Comment Id":
'+JSON.serialize(thisComment.Id)+', "Message" : "Comment submitted
successfully"}]');
}
}
The URL for the above API class will look like -
/services/apexrest/sendComment?commentTitle=Sample title&textBody=This is a comment

Resources