1

I'm trying to invoke the Google Natural Language Processing API from Salesforce using the OAuth authentication .I have received access_token from google cloud api but when I'm making call to API with body I'm receiving the INVALID_ARGUMENT and BAD REQUEST error.

HttpRequest req = new HttpRequest(); 
HttpResponse res = new HttpResponse();
Http h = new Http();
req.setHeader('ContentType','application/json');
req.setHeader('Content-length', String.valueOf(body_str.length()));
req.setHeader('Authorization', 'OAuth '+JWTToken_resp.access_token);
req.setMethod('POST');
req.setEndpoint('https://language.googleapis.com/v1/documents:analyzeSentiment?fields=documentSentiment'); 
//req.setEndpoint('https://language.googleapis.com/v1beta2/documents:analyzeSentiment '); 
String body_str ='{"document":{"type":"PLAIN_TEXT","language":"EN","content":"Lawrence of Arabia is a highly rated film biography about British Lieutenant T. E. Lawrence. Peter OToole plays Lawrence in the film."},"encodingType":"UTF8"}';
req.setBody(body_str); // Also tried req.setBody(JSON.serialize(body_str));
res = h.send(req);
System.debug('final nlp respone..'+res.getBody());

Receiving Below Error

System.HttpResponse[Status=Bad Request, StatusCode=400]

Detailed Error Message
{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"{\"document\":{\"type\":\"PLAIN_TEXT\",\"language\":\"EN\",\"content\":\"Lawrence of Arabia is a highly rated film biography about British Lieutenant T. E. Lawrence. Peter OToole plays Lawrence in the film.\"},\"encodingType\":\"UTF8\"}\": Cannot bind query parameter. Field '{\"document\":{\"type\":\"PLAIN_TEXT\",\"language\":\"EN\",\"content\":\"Lawrence of Arabia is a highly rated film biography about British Lieutenant T' could not be found in request message.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"{\"document\":{\"type\":\"PLAIN_TEXT\",\"language\":\"EN\",\"content\":\"Lawrence of Arabia is a highly rated film biography about British Lieutenant T. E. Lawrence. Peter OToole plays Lawrence in the film.\"},\"encodingType\":\"UTF8\"}\": Cannot bind query parameter. Field '{\"document\":{\"type\":\"PLAIN_TEXT\",\"language\":\"EN\",\"content\":\"Lawrence of Arabia is a highly rated film biography about British Lieutenant T' could not be found in request message."
          }
        ]
      }
    ]
  }
}

Any idea how to resolve this issue.

1 Answer 1

0

I got the solution ,the only problem is setting up the contenttype header wrongly. There should be an (-) hypon symbol between content and type.

**Changed From**
req.setHeader('ContentType','application/json');
**Changed To**
req.setHeader('Content-Type','application/json');

Hope this helps .

You must log in to answer this question.