I found some thread the same problem but their answers not works for me.
I have a post request to check user login.
Url form :
"http://support.xxx.xx:8031/serpapi/login/checkLogin"
Parameters :
["contextInfo" :
["clientId": "1000000", "orgId": "1000001",
"warehouseId": "1000002", "roleId": "0"],
"userName": "hanoiaUser", "password": "hanoiaUser"]
Request :
Alamofire.request(url!, method: .post, parameters: params).responseJSON { (response) in
print(response)
}
Error response :
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
Why am i getting this error? and how to solve it ?
Edit : i'm tried with POSTMAN and it return response :
Content-Type : application/json
Body : raw - json
{
"contextInfo" : {
"clientId":1000000,
"orgId": 1000001,
"warehouseId": 1000002,
"roleId": 0
},
"userName": "hanoiaUser",
"password": "hanoiaUser"
}
RESPONSE :
{
"success": true,
"data": [
{
"userId": 1000003,
"userName": "hanoiaUser",
"token": "b7e804d25065e5c3ac97d765180b7986"
}
],
"error": null
}
Ok, finally I solved the problem
Here's new request :
Alamofire.request(url!, method: .post,encoding : JSONEncoding.default, headers: headers, parameters: params).responseJSON { (response) in
print(response)
}
With Headers :
let headers = [
"Content-Type": "application/json"
]
Set the request header like :
request.allHTTPHeaderFields = ["Content-Type":"application/json"]
Related
I'm trying to use Wiremock Request Templating to generate a response from my request body.
I am unable to replace the newlines that are generated from the jsonPath helper, due to an open issue with Handlebars.java, I have had to resort to a strange hack to remove newlines. This works as expected, but when Wiremock attempts to deal with my request I get an error:
"Unexpected character ('f' (code 102)): was expecting comma to separate Object entries\\n at [Source: (String)\\"{\\"id\\":\\"05325128-01d8-406d-8067-4e8b587a8983\\",\\"person\\":{\\"crn\\":\\"C461082\\",\\"name\\":\\"Sherri Durgan IV\\",\\"dateOfBirth\\":\\"2022-08-31\\",\\"sex\\":\\"Female\\",\\"status\\":\\"InCustody\\",\\"nomsNumber\\":\\"NOMS662\\",\\"nationality\\":\\"Honduras\\",\\"religionOrBelief\\":\\"Buddhist\\",\\"prisonName\\":\\"HMP Emmerich Camp\\"},\\"data\\":\\"{ \\"foo\\" : \\"4%:S2lL$3G\\", \\"bar\\" : \\"+O}btr`,yM\\", \\"bike\\" : \\"'dn+#T;7[s\\", \\"a\\" : 65468, \\"b\\" : \\"mpVql:uMx.\\", \\"name\\" : \\"C'i,+5o{8Y\\", \\"prop\\" : \\"%tEqU;an:]\\", \\"basic-information\\" : { \\"sentence-type\\" : { \\"sentenceTyp\\"[truncated 31 chars]; line: 1, column: 286]"
Here's my request:
{
"request": {
"method": "PUT",
"url": "/applications/some-uuid",
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json;charset=UTF-8"
},
"jsonBody": {
"data": "{{{urlEncode (replace(urlEncode (jsonPath request.body '$.data')) '%0A' '') decode=true}}}",
},
"transformers": ["response-template"]
}
}
Any pointers gratefully received!
I have written the api call like this:
var response = await http.post(
Uri.parse("http://api.msg91.com/api/v2/sendsms"),
headers: {
"Content-Type": "application/json",
"authkey": "API key"
},
body: jsonEncode({
"sender": "note",
"route": "4",
"country": "91",
"flash": 1,
"sms":
{"message": "Message1", "to": "9999999999"}
}),
);
But this giving me error : {type: error, message: Invalid content type.Please send data in formdata,application/xml,application/json format, code: }
How can I correct this?
Try removing theses
"Content-Type": "application/json"
or replace it with
"Content-Type": "application/xml"
You should use multipart/form-data as content-type ->
"Content-Type": "multipart/form-data"
I'm fairly new to the swift and I'm facing a problem with Alamofire what I'm trying to do is sending a get request with json body but I'm stuck heres my code:
struct request {
func getMessage(message:String){
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
makeRequest(parameters: parameters)
}
func makeRequest(parameters:[String:Any]){
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",method: .post,parameters: parameters).response{
response in
debugPrint(response)
}
}
after executing this code i get:
[Request]: POST https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944
[Request Body]:
info%5Btoken%5D=&message%5Btype%5D=text&message%5Btext%5D=Karakter&recipentId=&type=message
[Response]:
[Status Code]: 415
[Headers]:
Accept: application/json
Content-Length: 0
Date: Sat, 07 Mar 2020 19:10:23 GMT
Server: cloudflare
cf-cache-status: DYNAMIC
cf-ray: 57069dc3eaccad06-OTP
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-b3-traceid: b10ba988c0249901
[Response Body]:
None
[Data]: None
[Network Duration]: 0.3303520679473877s
[Serialization Duration]: 0.0s
[Result]: success(nil)
i dont get any result body compared to what expect when i send this request over postman:
"result": {
"messages": [
{
"type": "text",
"text": "Karakter Analizine Hoşgeldiniz. Analize başlamak için \"karakter\" yazınız"
},
{
"type": "text",
"text": "Test"
}
],
"tag": [
"start",
"finish"
],
"conversation_id": "5e63f302dc4bec0001883f01",
"intent_name": "Default Karakter",
"intent_id": "5ccb46ef66d0ba0001dbfcdf",
"intent_score": null,
"current_flow_id": "ee52db21-dae1-4587-80cd-7649798dddce1583608578222"
}
so how can i send this post request with this given body below:
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
Now i have sent the request and got a body looking like this:
"result": {
"messages": [
{
"extra": {},
"question": "Adınız ?",
"type": "text",
"values": [
{
"text": ""
}
],
"askCount": 1,
"text": "Adınız ?",
"waitUserInput": true
}
],
"tag": [
"start",
"p_firstName",
1
],
"conversation_id": "5e63ffa0dc4bec0001883f10",
"intent_name": "Karakter Analizi",
"intent_id": "5cc20ae266d0ba0001dbf946",
"intent_score": "62.0",
"current_flow_id": "62ac3ac8-0cd7-43e5-b92b-f119d49c40d41583611808850"
}
how can i print the question variable to a label on my screen ?
Response code 415 means Unsupported Media Type and the Accept header of the response lets you know that the sever expects data to be sent as JSON. All you have to do is to let Alamofire know that it should encode parameters as JSON in the request body
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default).response { response in
debugPrint(response)
}
you need to mention the encoding type as well while sending request. since your parameters data is json add encoding parameter as encoding: JSONEncoding.default
for example i have used as:
manager.request(url, method: httpMethod,
parameters: parameters,
encoding: JSONEncoding.default,
headers: configuredHeader)
.validate(statusCode: 200..<300)
.responseJSON(completionHandler: { [weak self] response in
self?.handleNetworkResponse(response: response, networkCompletionHandler: networkCompletionHandler)
})
I am trying to provide a MOCK service that takes a headerName and value from the query and returns it as a (dynamic) header with the response. I am using the following response definition:
"response" : {
"status" : 200,
"statusMessage": "OK",
"headers" : {
"Content-Type" : "application/json",
"{{request.query.debugHeader}}" : "{{request.query.debugHeaderValue}}"
},
"jsonBody" : {
"headerSent": "{{request.query.debugHeader}} {{request.query.debugHeaderValue}}"
},
"transformers": ["response-template"],
"base64Body" : ""
}
The header value is correctly evaluated and put into the response template, however I can't get the header name to be taken from the request.
When sending a request:
http://localhost:8090/example?debugHeader=name&debugHeaderValue=value
The result headers I get back are:
HTTP/1.1 200 OK
Content-Type: application/json
{{request.query.debugHeader}}: value
However I want {{request.query.debugHeader}} to be replaced with the actual request parameter value ("name" in the example above).
Any ideas?
Thanks in advance
Alex
This is supported in WireMock.Net.
The request which you need to specify looks like this:
{
"Guid": "90356dba-b36c-469a-a17e-669cd84f1f05",
"Priority": 0,
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/trans",
"IgnoreCase": false
}
]
},
"Methods": [
"get"
]
},
"Response": {
"StatusCode": 200,
"BodyDestination": "SameAsSource",
"Body": "{\"msg\": \"Hello world : {{request.path}}\" }",
"UseTransformer": true,
"Headers": {
"Content-Type": "application/json",
"Transformed-Postman-Token_{{request.path}}": "token is {{request.headers.Postman-Token}}"
}
}
}
This will add the transformed header Transformed-Postman-Token_{{request.path}} in the response.
Presently this type of variability is not part of the out-of-the-box WireMock application and would have to be custom added. In the WireMock documentation the section Extending WireMock and in particular the part on Transforming Responses.
I'm having hard time doing something simple. The data I want to send is the following:
{
"nickname":"Rado",
"social": {
"data: {
"accesstoken":"xx",
"applicationId":"xx",
"userId":"xx"
},
"type":"whatever"
}
}
Currently I'm doing that:
let params = [
"nickname": userName,
"social": [
"type": "whatever",
"data": [
"userId": accessToken.userID,
"accesstoken": accessToken.tokenString,
"applicationId": accessToken.appID
]
]
]
Alamofire.request(.POST, "url/users", parameters: params, headers: nil)
.responseJSON { response in
}
As a response I get this:
{
"nickname":"Rado",
"social[data][userId]":"xx",
"social[data][applicationId]":"xx",
"social[data][accesstoken]":"xx",
"social[type]":"something"
}
Any advice will be appreciated!
The solution turned out to be really simple. I was missing encoding: .JSON
Alamofire.request(.POST, "url/users", parameters: params, headers: nil, encoding: .JSON)
.responseJSON { response in
}