Apex Class -->
public class Json_Callout{
public static string response;
// Pass in the endpoint to be used using the string url
public static string getContent() {
system.debug('++++++++++++++++++++++++++++In side the Method Get Content');
String url = 'http://180.211.69.30:8080/JhImpl/WS/implService/upload';
// Instantiate a new http object
Http h = new Http();
try {
system.debug('++++++++++++++++++++++++++++In side the Try Block');
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setHeader('abc', 'abc');
req.setEndpoint(url);
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
system.debug('Result==========================================='+res);
system.debug('REsult for Variable=============================='+res.getBody());
response = res.getStatus();
String contact = response;
return res.getBody();
}
catch(System.CalloutException ex) {
system.debug('catch'+ex);
}
}
}
Apex Page -->
<apex:page Controller="Json_Callout" tabStyle="Account">
It will be a nice to get output from the controller
<apex:pageBlock title="Hello {!$User.FirstName}!"/>
<apex:form >
<apex:commandButton value="Go!" action="{!getContent}"/>
</apex:form>
<!--<apex:variable var="c" value="{!contact}" />-->
<!--<apex:pageMessages>
</apex:pageMessages>-->
</apex:page>
How do i retrieve the Json Object , in order to Parse it.
I have system.debug the response.getBody() which is giving me the status code = 200 , that means i am able to hit the service , but how do i get the Json Object and the response so as to Parse it and also reflecting back it into the Apex Page .
I am getting the error that The name can only contain underscores and alphanumeric characters. It must begin with a letter and be unique, and must not include spaces, end with an underscore, or contain two consecutive underscores.
Thanks.
Related
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();
}
I am working on a project using angularjs+springboot. Am trying to send email via my application using spring-boot-starter-mail. The message and object of the email are written by the user in a form. what I want to do is to get the message and object values in my RestController using #RequestBody.
the function in my service.js
// send mail
var sendMail = function(id, objet, msg) {
var deferred = $q.defer();
$http.post(urlBase + id, objet, msg).then(
function(response) {
deferred.resolve(response.data);
}, function(errResponse) {
console.error('Error while sending email');
deferred.reject(errResponse);
});
return deferred.promise;
}
the method in my restContoller
#RestController
public class EmailController {
#Autowired
private JavaMailSender javaMailSender;
#Autowired
UtilisateurService service;
#RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(#PathVariable("id") int id, #RequestBody String objet,
#RequestBody String msg) {
Utilisateur currentUser = service.findById(id);
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(currentUser.getEmailUtil());
message.setSubject(objet);
message.setText(msg);
javaMailSender.send(message);
return new ResponseEntity<Void>(HttpStatus.OK);
}}
This throws this exception :
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Void> com.sla.utilisateur.controller.EmailController.sendMail(int,java.lang.String,java.lang.String)
How can I fix it?
thank you,
Your usage of $http.post is not correct. You should have a look at the AngularJS POST documentation. $http.post arguments are the following:
post(url, data, [config]);
AngularJS sends the data by default in JSON. So you should send the request using the following statement (for example):
$http.post(urlBase + id, {subject:objet, body:msg})
And in your controller you should define only one #RequestBody maps for the ease of the example to a Map (You could change it to a POJO. ):
#RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(#PathVariable("id") int id, #RequestBody Map<String,String> msg) {
Utilisateur currentUser = service.findById(id);
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(currentUser.getEmailUtil());
message.setSubject(msg.get("subject");
message.setText(msg.get("body"));
javaMailSender.send(message);
return new ResponseEntity<Void>(HttpStatus.OK);
}}
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.
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"])
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