Microsoft Translator Text API doesn't work - api

I want to use Microsoft Translator API but I am unable to use it.
I created a Microsoft Azure account as specified in the documentation (http://docs.microsofttranslator.com/text-translate.html) and I created a resource.
When I call the web service to get an access toke, every time I get an exception because a time out..
This is my code (it's Apex, similar to Java) :
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Length', '3495');
req.setEndpoint('https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key=[myAPIKey]');
req.setTimeout(20000);
HttpResponse res = h.send(req);
If I remove my API key or I the content length from the header, I get an error from Microsoft.
Do you know why I get this?
Thanks

You should replace [myAPIKey] with the right key. You can get it through https://www.microsoft.com/cognitive-services
EDIT
The answer above is related to GET operations. For POST, you should include the 'Ocp-Apim-Subscription-Key' header:
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Length', '3495');
req.setHeader('Ocp-Apim-Subscription-Key', '[INSERT_HERE_YOUR_TOKEN]');
req.setEndpoint('https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
req.setTimeout(20000);
HttpResponse res = h.send(req);

It works fin now.
I edit my code and it is ok :
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(theURL);
req.setHeader('Content-Type','application/xml');
Http binding = new Http();
HttpResponse res = binding.send(req);
Thanks

Related

The XML you provided was not well-formed or did not validate against our published schema: while calling S3 bucket from Salesforce

Folks,
A total newbie here when it comes to making end-to-end integrations. I am trying to "put" my salesforce data to the s3 bucket but receiving:
The XML you provided was not well-formed or did not validate against our published schema
Here's what I am doing:
List<Task> tasks = new List<Task>([SELECT ID from TASK WHERE Id =:recordId LIMIT 1]);
for(Task task:tasks)
{
try
{
//File Content
String Body = JSON.serialize(task);
HttpRequest req = new HttpRequest();
req.setMethod('PUT');
req.setEndpoint('callout:AWS_Credentials');
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody(Body);
Http http = new Http();
HTTPResponse res = http.send(req);
What might I be doing wrong here? Too lost to see..
Thanks in advance!
Set the content type as 'application/xml' instead of 'application/json;charset=UTF-8'
req.setHeader('Content-Type', 'application/xml');

JScript REST API: read a paginated list

In JScript I need to read a list of books from a web server that has a 2-step authentication i.e. user + password and token afterwards - once you call an IP address you get a token in response which needs to be used in a header for books (Authorization; Bearer + token). Server is supposed to respond with a paginated list of books
[{"book_Id": 1,"book_Name": "AAA","book_Year": 2021}].
Path is "GET /book", parameters are: "Page" and "Size". I've managed to call the server and get token in reponse:
var xmlhttp = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp.open("GET", "http://XX.XX.XX.XX:XXXX/authenticate?username=XXX&password=XXX", false);
xmlhttp.send();
var token = JSON.parse(xmlhttp.responseText).token
and tried to use it
var header = xmlhttp.SetRequestHeader("Authorization", "Bearer "+token)
new ActiveXObject("WScript.Shell").Popup(header.responseText)
but got empty response and got stuck. I'd very much appreciate being moved on with how to read the list.
Edit
So I've added new object and now get status 404 error Not Found. Is there some error in the coding yet?
var xmlhttp = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp.open("GET", "http://XX.XX.XX.XX:XXXX/authenticate?
username=XXX&password=XXX", false);
xmlhttp.send();
var token = JSON.parse(xmlhttp.responseText).token
var xmlhttp2 = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp2.open("GET", "http://XX.XX.XX.XX:XXXX/book?limit=1", false);
xmlhttp2.SetRequestHeader("Authorization", "Bearer "+token)
xmlhttp2.send();
new ActiveXObject("WScript.Shell").Popup(xmlhttp2.responseText)

restsharp get error (authentication)

I have a API GET call that works in postman BUT not in VS2017. I copied the code
from postman:
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "19763da3-4b00-4e92-83e0-1ac75f99d219");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
request.AddParameter("undefined", "{\n \"username\":\"domain\\\\username\",\n \"password\":\"myPasswd\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
The error I am getting is unauthorized, the API required a header of X-XSRF-TOKEN with a value of 71cf12361-8090-499a-adc3-2d5e98a04143 (a fake key)
Using postman, everything works just fine, but using VS2017 I get an error:
{"status":"unauthorized","error":"Login is required","errormsg":null}
What's weird (I am new to this so pardon my ignorance)is that the header does not contain:
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
but rather the parameter does, which is confusing since I thought the AddHeader would add it to the header but maybe I am misunderstanding something....
any advice/suggestions would be extremely welcomed
thank you in advance
dougc
Please use the below code and check
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
//Make sure to give the Valid Token
request.AddHeader("Authorization","X-XSRF-TOKEN <<Generated Token>>");
IRestResponse response = client.Execute(request);
Console.WriteLine("Response :" + response.Content);

API Connect 5 - Error attempting to read the urlopen response data

I'm trying to create a REST API from a SOAP Service using IBM API Connect 5. I have followed all the steps described in this guide (https://www.ibm.com/support/knowledgecenter/en/SSFS6T/com.ibm.apic.apionprem.doc/tutorial_apionprem_expose_SOAP.html).
So, after dragging the web service block from palette, ensuring the correctness of endpoint and publishing the API, I have tried to call the API from the browser. Unfortunately, the API return the following message:
<errorResponse>
<httpCode>500</httpCode>
<httpMessage>Internal Server Error</httpMessage>
<moreInformation>Error attempting to read the urlopen response
data</moreInformation>
</errorResponse>
To testing purpose, I have logged the request and I have tried the request on SOAPUI. The service return the response correctly.
What is the problem?
In my case, the problem was in the backend charset (Content-Type: text/xml;charset=iso-8859-1).
For example, backend returns text/xml in German (or French). Api Connect cannot process character ΓΌ. It needs Content-Type: text/xml;charset=UTF-8.
I had a similar issue, in my case was the accept. if you have an Invoke and the content-type or the accept, is not matching the one of the request, or the response that you got, APIC is getting mad.
Please, check if the formats to send (contentType) and receive (accept) are the same of that your API expected. In my case the error occurs because the API returns a String and my default code is configured to receive a JSON body.
//define a JSON-PLAIN TEXT protocol
private HttpEntity<String> httpEntityWithBody(Object objToParse){
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "xxx token xxx");
headers.set("Accept", MediaType.TEXT_PLAIN_VALUE);
headers.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new GsonBuilder().create();
String json = gson.toJson(objToParse);
HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
return httpEntity;
}
//calling the API to APIC...
ParameterizedTypeReference<String> responseType = new
ParameterizedTypeReference<String>(){};
ResponseEntity<String> result =
rest.exchange(builder.buildAndExpand(urlParams).toUri(), HttpMethod.PUT, httpEntityWithBody(myDTO), responseType);
String statusCode = result.getStatusCodeValue();
String message = result.getBody();

HTTPS REST call from salesforce returns error

I am trying to call a end point using following code, but it always returns the below error.
Can you suggest what is the possible error?
HttpRequest req = new HttpRequest();
req.setEndpoint('https://ntrs-com.apibasicauth.btglss.net/bitglassapi/data/v1/soql');
req.setMethod('POST');
//req.setHeader('Authorization', '');
req.setHeader('Content-Type', 'application/json');
req.setBody('{"responseformat":"json","query":"select Id from Account","offset":"1","limit":"10"}');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug('---Body----'+res.getBody());
Error says:
Line: 8, Column: 1 System.CalloutException:
java.security.cert.CertificateException: No subject alternative DNS
name matching ntrs-com.apibasicauth.btglss.net found.