How do you change the response content-type on Swagger?
I tried changing the media type to
"content" : {
"text/plain; charset=utf-8" :{ "ABC, XYZ"
}
Results in an error to remove additional properties
Related
Response response = new RestBuilder.post(finalUrl){
header: ["ticket", "getProxyTicket()",
"name", "abc",
"id", "1"
]
contentType: application/json
json data
}
I have the above code. And when I send the post request through API call, I get an exception "Proxy ticket must be sent as parameter in header". I don't know what is wrong with the code. Can anyone help me?
There are different ways to do it. This should work:
new RestBuilder().post(finalUrl){
// this will work if you want the value
// of the ticket header to be the literal "getProxyTicket()".
// if you are trying to invoke a method and you want the return
// value of that method to be the header value, remove the double
// quotes around getProxyTicket()
header "ticket", "getProxyTicket()"
header "name", "abc"
header "id", "1"
// no need to set the content type, the
// json method below will do that
// contentType: application/json
json data
}
I am experiencing the weirdest error while using RestKit. Here's the localized description of the error -
Expected content type {(
"application/json",
"text/html",
"text/plain",
"application/x-www-form-urlencoded"
)}, got {application/json}
As you can see, I am expecting "application/json" as a content type, and the server is returning application/json. I have no idea why I am getting this error!
The detailed error is here --
2015-02-19 11:24:43.234 MyProject[62944:10754151] E restkit.network:RKObjectRequestOperation.m:213 POST 'https://ipaddress/api/v1.0/user/verify' (200 OK / 0 objects) [request=0.1408s mapping=0.0000s total=0.1428s]: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1016 "Expected content type {(
"application/json",
"text/html",
"text/plain",
"application/x-www-form-urlencoded"
)}, got {application/json" UserInfo=0x7f9c49db4930 {NSLocalizedRecoverySuggestion={"user_id":"3749f17f647c4ee1a9ee9d75c5f49f7e","domain":"domain","device_id":"2751029764","access_token":"589134b447974320b2d494a491e8226a","access_token_expiration":2181237828314,"refresh_token":"cb06c038be7b4f7c930de1fcb3f2017a"}, NSErrorFailingURLKey=https://ipaddress/api/v1.0/user/verify, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0x7f9c49def0c0> { URL: https://ipaddress/api/v1.0/user/verify }, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7f9c49f567a0> { URL: https://ipaddress/api/v1.0/user/verify } { status code: 200, headers {
"Baseline-Request-Id" = 30f91b50;
Connection = "keep-alive";
"Content-Length" = 230;
"Content-Type" = "{application/json, q=1000}";
Date = "Thu, 19 Feb 2015 19:23:48 GMT";
Server = "nginx/1.6.2";
} }, NSLocalizedDescription=Expected content type {(
"application/json",
"text/html",
"text/plain",
"application/x-www-form-urlencoded"
)}, got {application/json}
Update --
After some debugging, I found out that the problem lies in the value of "Content-Type" I am getting in the response. As you can see in the example above, the value is "{application/json, q=1000}" instead of "application/json". RestKit, for some reason, is reading it as "{application/json" (omitting the stuff after the comma, and notice the starting brace) and hence not finding a match with the expected types.
To "solve" it in a dirty way, I added the following line (notice the "{" before "application/json")
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"{application/json"];
But we all know its not the right way. I don't know what is wrong here, is the server sending something incorrect? Or is RestKit supposed to read it differently?
I couldn't find the reason why the server was returning a "Wrong" content type. The developers of the server denied that it was doing something wrong. So I ended up using my dirty hack and added a "{" before "application/json".
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"{application/json"];
The code part:
function PushRequests(strUser, eClientType, iSectorId, strDeviceId, arrRequests) {
var input = {
method : 'post',
returnedContentType : 'xml',
path : 'SomeAddress/PushRequests',
parameters : {
'strUser' : strUser.toString(),
'eClientType' : eClientType.toString(),
'iSectorId' : iSectorId.toString(),
'strDeviceId' : strDeviceId.toString(),
'arrRequests' : arrRequests // <- the array
}
};
return WL.Server.invokeHttp(input);
}
The response:
Procedure invocation error. Content is not allowed in prolog.,Failed to parse the payload from backend (procedure: HttpRequest)
I have tried to strignify the array by the navite way and via JSON. This is not the solution.
I know the problem is with the array passed. Does anybody know a workaround, or a way to correctly pass an array to the adapter?
I know the problem is with the array passed.
How do you know this?
Content is not allowed in prolog.
This is almost always a symptom of passing data to an XML parser that is invalid XML, or has some characters before the prolog, which is:
<?xml version="1.0" encoding="utf-8"?>
In your adapter, you've told it to expect XML from the backend HTTP service you're calling. I was able to reproduce the same message you see by returning invalid XML from my backend HTTP service. In fact, I can put anything in the response that is invalid XML, and I'll get the "Content is not allowed in prolog." message. I can return a page that is a 404 page, or with a Content-Type header of "text/plain". The adapter was told to expect XML, but given something else.
Please be sure to check that you are not getting a 404 page, or 500, or something else from the backend HTTP service your adapter is calling.
Here's how I reproduced the "Content is not allowed in prolog" message from my adapter:
First, create an adapter with xmltester.xml:
<wl:adapter name="xmltester"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.worklight.com/integration"
xmlns:http="http://www.worklight.com/integration/http">
<displayName>xmltester</displayName>
<description>xmltester</description>
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>http</protocol>
<domain>localhost</domain>
<port>3000</port>
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="2" />
</connectivity>
<procedure name="getStuff"/>
</wl:adapter>
and xmltester-impl.js:
function getStuff() {
var input = {
method : 'get',
returnedContentType : 'xml',
path : 'index.xml',
parameters : {
'arrRequests' : JSON.stringify(['one', 'two'])
}
};
return WL.Server.invokeHttp(input);
}
I created a node server (server.js) to be my backend:
var express = require('express');
var app = express();
var port = 3000;
app.get('/index.xml', function(req, res){
var body = '<?xml version="1.0" encoding="utf-8"?><boo/>';
res.setHeader('Content-Type', 'application/xml');
res.setHeader('Content-Length', body.length);
res.end(body);
});
app.listen(port);
console.log('Listening on port %s', port);
Started the server:
npm install express
node server.js
Then created a Worklight app with a button:
<button id="doit">Do it!</button>
And linked up a click listener to see what I get back from Worklight when the adapter is invoked:
$ = WLJQ;
$("#doit").click(function() {
var invocationData = {
adapter : 'xmltester',
procedure : 'getStuff',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : function(data) {alert("SUCCESS" + JSON.stringify(data));},
onFailure : function(data) {alert("FAILURE" + JSON.stringify(data));}
});
return false;
});
I could recreate the problem exactly when my backend server returned a payload with extra characters in front of the prolog (which you can try yourself by editing the server.js code above), like:
somethinghere<?xml version="1.0" encoding="utf-8"?>
Or any non-XML payload, for that matter.
returnedContentType : 'xml'
Failed to parse the payload from backend
Is the returned content in xml format? If not, can you cange the returnedContentType field to 'plain' or 'html' or whichever format you are expecting it in?
I'm trying to delete an entry from the database by odata. I get the error message
{"error":{"code":"","message":{"lang":"en-US","value":"Bad Request - Error in query syntax."}}}
my code:
function deleteMonthEntry() {
var item = actMonthEntries.getItem(listIndex);
var queryString = "Stundens(" + item.data.datensatz_id + ")?$format=json";
var requestUrl = serviceUrl + queryString;
WinJS.xhr({
type: "delete",
url: requestUrl,
headers: {
"Content-type": "application/json"
}
}).done(
function complete(response) {
},
function (error) {
console.log(error);
}
);
}
My request URL looks like this:
requestUrl = "http://localhost:51893/TimeSheetWebservice.svc/Stundens(305233)?$format=json"
Thanks
Marlowe
At least I found the solution:
I've entered an filter request to my service like this:
TimeSheetWebservice.svc/Stundens?$filter=datensatz_id eq 305221
this returned the correct entry with this link:
TimeSheetWebservice.svc/Stundens(305221M)
So if I enter a M after the ID, everything works fin. But I have no idea where this M comes from.
Can anyone tell me the reason for this M? It does not belong to the ID. The ID is this
305221
Marlowe
Are you sure the server you're talking to supports the $format query option? Many don't. I would try removing that part of the request URI, and instead modify your headers value to specify an Accept header:
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
For servers where $format is allowed, giving it a json value is equivalent to providing an Accept header with the application/json MIME type.
In general, for a DELETE operation, the Accept header or $format value only matters for error cases. With a successful DELETE, the response payload body will be empty, so there's no need for the server to know about your format preference.
am just starting off with restkit for ios. I have a very simple json response
{
"result": [
{
"userid": "5964",
"name": "Your Name"
}
]
}
This is a valid json (tested against jsonlint)
However, when i try to use this with RKClient, it doe'snt see it as json. This is my code
-(void) request:(RKRequest *)request didLoadResponse:(RKResponse *)response{
if([request isGET]){
if([response isJSON]){
NSLog(#"JSON Response from Server %#", [response bodyAsString] );
}else{
NSLog(#"Non JSON Response from Server %#", [response bodyAsString] );
}
}
}
It always logs "Non JSON Reponse...." but the json is perfectly valid. The same thing happens when i use RKObjectMapping; the error will be "Unable to find parser for MIME Type text/xml.
Any help is highly appreciated.
Thanks
If for any reason you can't change the server headers and returned Mime type to xml or json, you can still add mapping for mime type 'text/html' to be processed as json.
Just add :
[[RKParserRegistry sharedRegistry] setParserClass:[RKJSONParserJSONKit class] forMIMEType:#"text/html"];
And don't forget to add the related header file :
#import <RestKit/RKJSONParserJSONKit.h>
Works for me.
Have a look at https://github.com/RestKit/RestKit/wiki/Using-a-Custom-MIME-Type
Serveur response header should be "application/json", and not "text/xml". ;p
I was a bit dumb, but things got solved once i added
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
to the server script.