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
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 want to pass two parameters in axios post method one as requestBody and one as requestParam and also i need to pass authHeader as a header .
This is the axios method to post new senior with his image:
create(data,file) {
return http.post("/addSenior", data,{ headers: authHeader()});
}
and this is the controller with two parameters :
#PostMapping("/addSenior")
#ResponseBody
#Operation(security = {#SecurityRequirement(name = "bearer-key")})
public long addSenior(#RequestBody Senior s,#RequestParam("file") MultipartFile file) throws Exception{
FileDB attachment = null;
String downloadURl = "";
attachment = storageService.store(file);
downloadURl = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/download/")
.path(attachment.getId())
.toUriString();
return seniorServiceImpl.addSenior(s,attachment.getId());
}
Normally, when you need to send a file along with some other data in spring mvc, you can use #RequestPart instead of #RequestParam. In your case, you can use something like this:
public long addSenior(#RequestPart Senior s, #RequestPart("file") MultipartFile file)
How do I use Azure AD Graph to update values on the AdditionalValues dictionary for a user? The test below returns 400 Bad Response.
Background:
The rest of my application uses MSGraph. However, since a federated user can not be updated using MSGraph I am searching for alternatives before I ditch every implementation and version of Graph and implement my own database.
This issue is similar to this one however in my case I am trying to update the AdditionalData property.
Documentation
[TestMethod]
public async Task UpdateUserUsingAzureADGraphAPI()
{
string userID = "a880b5ac-d3cc-4e7c-89a1-123b1bd3bdc5"; // A federated user
// Get the user make sure IsAdmin is false.
User user = (await graphService.FindUser(userID)).First();
Assert.IsNotNull(user);
if (user.AdditionalData == null)
{
user.AdditionalData = new Dictionary<string, object>();
}
else
{
user.AdditionalData.TryGetValue(UserAttributes.IsCorporateAdmin, out object o);
Assert.IsNotNull(o);
Assert.IsFalse(Convert.ToBoolean(o));
}
string tenant_id = "me.onmicrosoft.com";
string resource_path = "users/" + userID;
string api_version = "1.6";
string apiUrl = $"https://graph.windows.net/{tenant_id}/{resource_path}?{api_version}";
// Set the field on the extended attribute
user.AdditionalData.TryAdd(UserAttributes.IsCorporateAdmin, true);
// Serialize the dictionary and put it in the content of the request
string content = JsonConvert.SerializeObject(user.AdditionalData);
string additionalData = "{\"AdditionalData\"" + ":" + $"[{content}]" + "}";
//additionalData: {"AdditionalData":[{"extension_myID_IsCorporateAdmin":true}]}
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Patch,
RequestUri = new Uri(apiUrl),
Content = new StringContent(additionalData, Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(request); // 400 Bad Request
}
Make sure that the Request URL looks like: https://graph.windows.net/{tenant}/users/{user_id}?api-version=1.6. You need to change the api_version to "api-version=1.6".
You cannot directly add extensions in AdditionalData and it will return the error(400).
Follow the steps to register an extension then write an extension value to user.
Register an extension:
POST https://graph.windows.net/{tenant}/applications/<applicationObjectId>/extensionProperties?api-version=1.6
{
"name": "<extensionPropertyName like 'extension_myID_IsCorporateAdmin>'",
"dataType": "<String or Binary>",
"targetObjects": [
"User"
]
}
Write an extension value:
PATCH https://graph.windows.net/{tenant}/users/{user-id}?api-version=1.6
{
"<extensionPropertyName>": <value>
}
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"])
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.