POST Adapter HTTP Worklight 6 500 Server Error - json

I am trying to register a user in my Hybrid Worklight application. For this I am using an external REST API. The API says:
Request Method: POST
Request URL: https://${domainservice}/service/plan/${planName}/user?key=${key}&tenantId=${tenantId}
Request Headers: Content-Type:application/json
Request Payload:
{
"uid": "patricia",
"firstName": "Patricia",
"lastName": "Mayo",
"pic": "BASE64_ENCODED_IMAGE"
}
Field description:
uid (required): user's uid
firstName (optional): user's first name
lastName (optional): user's last name
pic (optional): user's picture encoded as base64 string
So I created a HTTP Worklight adapter:
function RegisterUser(userid) {
var input = {
method : 'post',
path : '/service/plan/App/user',
returnedContentType : 'plain',
headers: {'Content-Type' : 'application/json'},
parameters: {
'key':'e634bc60-0c6eba577258',
'tenantId': 'd93b921d-a56c-a645924fd548'
},
body : {
'contentType' : 'application/json',
'content' : JSON.stringify({
"uid" : userid})
}
};
return WL.Server.invokeHttp(input);
}
And I get this error:
{ "errors": [
],
"info": [
],
"isSuccessful": true,
"responseHeaders": {
"$wsep": "",
"Connection": "Keep-Alive",
"Content-Language": "en-US",
"Content-Type": "text\/html;charset=ISO-8859-1",
"Date": "Wed, 30 Jul 2014 14:47:27 GMT",
"Transfer-Encoding": "chunked",
"X-Backside-Transport": "FAIL FAIL",
"X-Client-IP": "199.127.32.67",
"X-Global-Transaction-ID": "48515650",
"X-Powered-By": "Servlet\/3.0"
},
"responseTime": 357,
"statusCode": 500,
"statusReason": "Internal Server Error",
I think is very weird that I set up
headers: {'Content-Type' : 'application/json'}
but in the response it looks like
"Content-Type": "text/html;charset=ISO-8859-1"
Also I want to point out some things I have already tried:
returnedContentType : 'plain' --> It is set to plain because if I set it to json I would get a JSON parse error
body content I also tried
var payload = "{\'uid\': \'"+userid+"\'}";
payload = payload.toString();
and then 'content' : payload
Using the RESTClient of the browser everything works fine
I tried using http port 80, http port 2080, and also https 443
I also tried writting the Host in the headers

I would not be too concerned about the format of the payload in the case where the server has hit an error condition - ideally servers would give us nicely formed error response but that's not always possible. Typically, if the expected response type in case of success is JSON then that's what I specify, and I just have to have enough error handling for cases when JSON parsing fails.
As to why you're getting the 500 error ... best I can suggest is to use a network monitor of some sort to discern the difference between the request issued via Worklight and the request as issued by the Browser's REST client.
You can set this up in Eclipse, Preferences->Run->TCP/IP Monitor ...

You may want to add a Host header. I've seen numerous times where it solved similar issues. E.g. if you're trying to connect to http://www.server.com/a/b/c/d add below header to your headers property
headers: {
Host: 'www.server.com'
}

I finally found the error. There is a defect in Worklight, the query parameters are removed and put into request body so the REST SERVICE does not receive key & tenantId. This is the final working code solution. Thank you anyways for your quick answers :)
function RegisterUser(userid) {
var payload = '{"uid": \"'+userid+'\"}';
var input = {
method : 'post',
path : '/service/plan/App/user?key=e630-db87-4803-bc45-57725c&tenantId=d9348af-a56c-a645924fd54e',
returnedContentType : 'application/json',
headers: {'Content-Type' : 'application/json'},
body : {
'contentType' : 'application/json',
'content' : payload.toString()
}
};
return WL.Server.invokeHttp(input);
}

Related

Unable to Print a JSON Object in Node js with "content-type": "text/plain; charset=UTF-8"

I am trying to print JSON object i.e. req.body in NodeJS using the below commands, but using JSON.stringify doesn't help. Could someone please suggest/guide how I can print this JSON object req.body
console.log("printing body: "+JSON.stringify(req.body))
console.log("printing body: "+req.body)
console.log("printing headers: "+JSON.stringify(req.headers))
Output:
printing body: {}
printing body: [object Object]
printing headers: {
"x-amz-sns-message-type": "SubscriptionConfirmation",
"x-amz-sns-message-id": "3dd623ert-7203-4e12-bf11-36589f9dce65",
"x-amz-sns-topic-arn": "arn:aws:sns:us-west-2:33030356879323:testTopic10",
"content-length": "1520",
"content-type": "text/plain; charset=UTF-8",
"host": "example.com",
"connection": "Keep-Alive",
"user-agent": "Amazon Simple Notification Service Agent",
"accept-encoding": "gzip,deflate"
}
Guidelines to Parse the JSON Object given by Amazon SNS:
In step 1: Point 2 of this document it advises
Use a JSON parser that handles converting the escaped representation
of control characters back to their ASCII character values (for
example, converting \n to a newline character). You can use an
existing JSON parser such as the Jackson JSON Processor
(http://wiki.fasterxml.com/JacksonHome) or write your own.
EDIT 1:
As you may see the printed headers, they have content-type": "text/plain; charset=UTF-8, could this be the reason why the bodyparser.json() doesn't work and we are unable to use JSON.stringify()
EDIT 2
Here is my body parsing code.
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // Used to parse the JSON request
app.use(bodyParser.urlencoded({ extended: true }));
EDIT 3:
SAMPLE OF THE RAW BODY THAT IS SENT IN THE REQUEST
{
"Type" : "SubscriptionConfirmation",
"MessageId" : "4c3232a-f297-4fba-96e8-dc821a0b2621",
"Token" : "2336412f37fb687f5d51e6e241d59b68c4e23a8e1a7b89aecf0dd7e227b0cf8ce107c9d1a4216d1aaf7dcdf66c18f0e06f1811a98351ced5018395453fee6f7e12fd5962220e0a81431063914e7b8d0c5340baeaf9dd2fe12e5288fbb88405fca2136c026d2b04e709e8ab6",
"TopicArn" : "arn:aws:sns:us-west-2:3303035234123:testTopic10",
"Message" : "You have chosen to subscribe to the topic arn:aws:sns:us-west-2:33030123453:testTopic10.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"SubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-west-2:33030234243413:testTopic10&Token=2336412f37fb687f5d51e6e241d59b68c4e58148956199a8e1a7be0dd7e227b0cfer1aaf7dcdf66c18f0e06f1811a98351ced5018395453fee6f7e12fd5962220e0a81431063914e7b8d0c5340baeaf9dd2fe12e5288fbb88405fca2136c026d2b04e709e8ab6",
"Timestamp" : "2017-09-04T13:06:36.005Z",
"SignatureVersion" : "1",
"Signature" : "QRy9574PIfSuNReyGEgDO86/utgF7R5enCmQTYBsUIdN0ohF9jWzh+qU9FLDp7EIXzg6Q3bLoI3HeYzNE4iMLHATixf2Iz29e0/ekWaMBewj+Q+pt42tKDh9YndRmyE2CSRJ7LTnvTVpS3MUgDI/kaQKmThxgN9wb8y8gebojuIE6zNAbYmuVVA+W6rIiF+dyG9e+f89dWSSReITB19XaVtLZ/BrcQWRyrBRFE06lXxYuGaLUIfTvItleaxX/BxKnNdxUL04sRNQ==",
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-433026a4050d206028891123453da859041.pem"
}
JSON.stringify() did print out the object. The object is just empty, i.e {}.

How to perform PUT operation to update an API in Jmeter?

Below code is for POST API:
{
"request": {
"method": "GET",
"urlPattern": "/identity/v2/users/7983739"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body" : "{ 'language': 'en‐US', 'phoneNumbers': [{'type': 'home','value': 8059662323}, {'type': 'office','value': 8053088006},{'type': 'mobile','value': 6502229400}],'addresses': [{‘address1': '419 State St’,’address2': '2nd Floor’,’city': 'Santa Barbara’,’state': ‘CA’,’postalCode': 93101,’country': ‘US’,’type': ‘shipping'}] }"
}
}
Now, I want to update the body with the below data:
"body" : "{'language':'en‐US','phoneNumbers':[{'type':'home','value':8059662323},{'type':'home','value':6502229400}],'addresses':[{'address1':'419 State St','address2':'2nd Floor','city':'Santa Barbara','state':'CA','postalCode':93101,'country':'US''type':'shipping'}]}"
Can someone tell me how to do it using Jmeter...
Here are the steps:
Add HTTP Request Sampler to your Test Plan
Configure host, port, URL, etc.
Select "PUT" from "Method" dropdown
Switch from "Parameters" to "Body Data" section
Provide new JSON value there
You might also need to add HTTP Header Manager to send at least Content-Type header with the value of application/json.
See Testing SOAP/REST Web Services Using JMeter article for detailed information on how to get started with API testing using JMeter
you can have the entire body in a variable and then user it here with ${variable}
you can also check here http://fabiouechi.blogspot.com/2011/03/jmeter-posting-json-data-to-web-service.html

"400 JSON parsing error" when send post to GCM

I am using Meteor for sending a request to GCM but I received message
error: 400 JSON_PARSING_ERROR
I do not understand what is wrong with my code:
options = {
"params": {
"registration_ids": "def",
"data": {"message":"abc"}},
"headers": {"Content-type":"application/json",
"Authorization": "key=AIzaSyCDCKsZ9BdJie99TC1GCdsZ1kke_oVbzw8"
}
}
HTTP.call("POST", 'https://android.googleapis.com/gcm/send', options);
I'm not familiar with meteor, but after a quick look at the doc...
What you have under params is expected to be request body, so I guess you should use content or data instead.

dojo/request/xhr calling Perl Web Service on different domain -getting scripting errors

I understand Dojo's XHR mechanism supports CORS but sets the X-Requested-With by default. I just have to set the headers = {"X-Requested-With":null }
So I am using dojo/request/xhr to call a Perl Web Service (Catalyst Framework)
xhr.get(url, {
handleAs: "json",
headers: {"X-Requested-With": null}
I'm using Fiddler and this is the JSON string:
{
"data" : [
{
"structure" : [
{
"name" : "State"
}
],
"dataSource" : [
{
"State" : "CA",
"Id" : 1
}
]
}
]
}
Fiddler returns an HTTP Result of 200 but I'm getting an error in dojo.then{}
"Unable to load http://Server:3000/state/ status: 0"
I also tried using dojo/request/script to call a Perl Web Service (Catalyst Framework)
script.get(url, {
jsonp: "callback"
}).then(...
But I get scripting error:
JavaScript critical error at line 2, column 11 in http://Server:3000/state/?callback=dojo_request_script_callbacks.dojo_request_script0\n\nSCRIPT1004: Expected ';'
It highlights the ":" after "data". I don't believe this ill-formed json string because my MVC controller method can call the Perl Server using WebClient's DownloadStringTaskAsync and return the value as a ContentString.
Any ideas??
If you're using CORS, you have to do more than just setting an X-Requested-With header. You also have to make sure the server sends the right headers, it had to send the Access-Control-Allow-Origin header and probably also the Access-Control-Request-Header header, for example:
Access-Control-Allow-Origin: *
Access-Control-Request-Header: x-requested-with
If you're using JSONP, your webservice must support JSONP, which means it's wrapping the entire result in a callback function.

Ajax request Syntax issue

Here my code in sencha for receiving JSON data, Problem is when i call is always shows the error message because of syntax.I dont know where it fails coz im new to sencha,Here my code
Ext.Ajax.request({
url: 'http://117.218.59.157:8080/WishList/Login',
method: 'POST',
headers: { 'Content-Type': 'application/json;' },
jsonData:{
username : "faz#gmail.com",
emailId : "faz"
},
success: function (response)
{
alert(response.responseText);
},
failure: function (response)
{
alert(response.responseText);
}
});
When the above method calls it showing the following response
<html><head><title>Apache Tomcat/7.0.14 - Error report</title><style><!--H1 {font-
family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;}
H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-
size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-
color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-
serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-
serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-
serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color :
black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - </h1><HR
size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The requested resource () is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.14</h3></body></html>
I call the JSON url in fiddler as in the following format
Method: POST
URL: http://117.218.59.157:8080/WishList/Login
Request:
{
"emailID": "xy#gmail.com",
"password": "ganesh"
}
Response:
[
{
"response": "Success"
}
]
I dont know where my code fails .please help me to sort it out
HTTP status 404 means "resource not found." The server at 117.218.59.157:8080 isn't configured to serve a resource on the path /WishList/Login. You'll have to look at the server configuration/code to figure out why that is. Note that some HTTP servers are case-sensitive, and so (for instance) WishList and Wishlist may not be the same thing to the server.
Personally I use a google chrome extension to check the services I call via Ajax in order to make sure they are OK. This one helped me a lot you just put your URL in there and mimics the GET/POST -- https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
Good Luck!