I have to send by post to a URL string of JSON text, I use a TidHTTP component for sending by post as shown in the code below, but when I hit the submit button I skip this error, I've been searching google to another people that this happens but none of the solutions have helped me in this case.
var
postData:String;
url:String;
contestacion:String;
datosPOst:TStringList;
lista:TMemoryStream;
begin
datosPOst:=TStringList.Create;
datosPOst.Text:='{'+#10+'"ticketCode": "asdasd",'+#10+
'"CIF": "***",'+#10+
'"storeCode": "***",'+#10+
'"saleTimeStamp": "\/Date(123456000000)\/",'+#10+
'"email": "prueba#***",'+#10+
'"userCP": "30280",'+#10+
'"products": ['+#10+
'{'+#10+
'"Amount": 1,'+#10+
'"Description": "PRUEBA ticket",'+#10+
'"Name": "Prueba ticket 2",'+#10+
'"Price": 25.25,'+#10+
'"ProductCode": "50",'+#10+
'"Tax": 21,'+#10+
'"UnitPrice": 250.00'+#10+
'}'+#10+
'],'+#10+
'"user": "****",'+#10+
'"password": "****"'+#10+
'}';
lista:=TMemoryStream.Create;
datosPOst.SaveToStream(lista);
contestacion:=conexion.Post('http://****.com/Ticket.svc/rest/InsertTicket',lista);
Also if there is any way to form a json from delphi also would appreciate
Thanks
Now I have the solution:
conexion.Request.ContentType:='application/json';
And is working
Error 400 is a reply you get when there are errors in your JSON.
I would advise using another component to send your POST request, a component that does give you the body text back, because that's what you need.
Synapse has an alternative to idHTTP.
Related
I am a beginner at web development and I am trying to use Postman to send a POST request to one of my application's APIs.
I am using the Next.JS framework to build my website.
Here is my API:
import type { NextApiRequest, NextApiResponse } from "next"
export default async (
req: NextApiRequest,
res: NextApiResponse,
) => {
const userData = JSON.parse(req.body)
res.status(200).json(userData)
}
I simplified my API until I caught the error, and I believe that it is related to the JSON.parse(req.body) line.
This is a print of the data that I used to test the API on Postman
I get the following error:
SyntaxError: Unexpected number in JSON at position 1
at JSON.parse (\u003canonymous\u003e)
at __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./pages/api/login.ts:9:27)
Previously, I used this API to authenticate users, and everything worked fine, except when I tried to insert data into the body of a Postman POST request.
Can someone help me? I have no idea what to do.
If you want to deserialize the body from a POST request, you also have to send a request where the body contains any data because otherwise, req.body will be null and that is not valid json.
Spring REST API is responding with following response:
On successful execution : It returns me a response of Text type.
On unsuccessful execution : It returns me JSON error object.
Front-End Service Class :
private detailsURL = 'http://localhost:8080/register';
constructor(private http:HttpClient){}
register(regisDetails): Observable<any>{
return this.http.post(this.detailsURL,regisDetails);
}
Front-End Component Class:
registerUser(){
this.service.register(this.regisForm.value).subscribe(
success => this.successMessage = success,
error => this.errorMessage = error.error.errorMessage
);
}
In case of error I'm getting the error message I'm supposed to get. But in case of success I'm not getting the successMessage.
Just wanted to know if there's any way to fetch the Text type response on front end. Or else I'll have to change my backend to send response of JSON Type for successful execution as well.
Please help me understand this thing.
You have to set the status for your response. In the controller part you have to mention consumes="application/json" in api request.
You should be doing your changes at the backend and provide the response in Json format response for both the success and backend. That would be the ideal solution.
It is really a bad design to provide a different response than what is expected. You could check the value of the header in request "accept:application/json" and provide response as was expected by the front end
Front End Fix :
However, in the front end you could always use
JSON.parse(success) to convert the text to Json object and use it further as required.
I'm guessing I've missed something silly so I apologize in advance.
I'm trying to run the example found at the following URL in mock mode: https://github.com/apigee-127/a127-samples/blob/master/weather-basic/api/swagger/swagger.yaml
The JSON response looks like it's being escaped and it's causing the response validator to fail:
{
"message": "Response validation failed: invalid content type (text/plain). These are valid: application/json",
"failedValidation": true,
"originalResponse": "{\"base\":\"Sample text\",\"clouds\":{\"all\":1},\"cod\":1,\"coord\":{\"lat\":1,\"lon\":1},\"dt\":1,\"id\":1,\"main\":{\"humidity\":1,\"pressure\":1,\"temp_max\":1,\"temp_min\":1,\"temp\":1},\"name\":\"Sample text\",\"sys\":{\"country\":\"Sample text\",\"id\":1,\"message\":1,\"sunrise\":1,\"sunset\":1,\"type\":1},\"weather\":[{\"description\":\"Sample text\",\"icon\":\"Sample text\",\"id\":1,\"main\":\"Sample text\"}],\"wind\":{\"deg\":1,\"speed\":1}}"
}
Any ideas would be awesome!
You need to send something like this res.json({});
Send as json object don't stringify your result object ,
var result = {name:"asdf",id:1212}
res.json(result);
I'm using Ember-Data 1.0.0.Beta-9 and Ember 1.7 to consume a REST API via DreamFactory's REST Platform. (http://www.dreamfactory.com).
I've had to extend the RESTAdapter in order to use DF and I've been able to implement GET and POST requests with no problems. I am now trying to implement model.save() (PUT) requests and am having a serious hiccup.
Calling model.save() sends the PUT request with the correct data to my API endpoint and I get a 200 OK response with a JSON response of { "id": "1" } which is what is supposed to happen. However when I try to access the updated record all of the properties are empty except for ID and the record on the server is not updated. I can take the same JSON string passed in the request, paste it into the DreamFactory Swagger API Docs and it works no problem - response is good and the record is updated on the DB.
I've created a JSBin to show all of the code at http://emberjs.jsbin.com/nagoga/1/edit
Unfortunately I can't have a live example as the servers in question are locked down to only accept requests from our company's public IP range.
DreamFactory provides a live demo of the API in question at
https://dsp-sandman1.cloud.dreamfactory.com/swagger/#!/db/replaceRecordsByIds
OK in the end I discovered that you can customize the DreamFactory response by adding a ?fields=* param to the end of the PUT request. I monkey-patched that into my updateRecord method using the following:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
And poof we haz updates!
DreamFactory has support for tacking several params onto the end of the requests to fully customize the response - at some point I will look to implement this correctly but for the time being I can move forward with my project. Yay!
EmberData is interpreting the response from the server as an empty object with an id of "1" an no other properties in it. You need to return the entire new object back from the server with the changes reflected.
I'm trying to post a json data via Arduino.When ı'm trying to this code.ı will send a json data with QueryString.If ı try this code the server answer me with Wrong QueryString format.Which mean is ı'm connected to server and server got my data.
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("POST /URL?query=jsondata HTTP/1.1");
client.println("Host: **.**.**.**");
client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
}
But My Main Plan is send my json data with querystring.If ı Try this code ;
client.println("POST /URL?query={request:{Header:{Username:kullaniciAdi,Password:123456},Item:{Serial:ABC123QWE,Data:100, DateOn:23/11/1986 15:45:24}}} HTTP/1.1");
I get a HTTP Error 400. The request is badly formed.
Anyone Has a any idea?
Yes, your URI contains spaces and may contain other characters to confuse the format of the post request. You need to encode these characters.
As far as I can tell, the Arduino standard libraries do not include any form of urlEncode method, which is common in other languages and libraries, so you will either have to create your own or look for one.
Your resulting code would be something like:
String request = "/URL?query={request:{Header:{Username:kullaniciAdi,Password:123456},Item:{Serial:ABC123QWE,Data:100, DateOn:23/11/1986 15:45:24}}}";
String encRequest = uriEncode(request); // need to write your own method for this...
String post = "POST " + encRequest + " HTTP/1.1");
client.println( post);
Some discussion on creating a uriEncode function is on the Arduino Forum and there also appears to be a working method on hardwarefun.com