I've use the AFNetworking in my app.
When I'll use the AFN with field EMAIL appear this error:
Error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: not found (404)" UserInfo=0x1096634a0 {NSLocalizedDescription=Request failed: not found (404), NSErrorFailingURLKey=http://mywebservice/vlemail?email=me%40domain.com, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x109558d10> { URL: http://mywebservice/vlemail?email=me%40domain.com } { status code: 404, headers {
Connection = "keep-alive";
"Content-Length" = 967;
"Content-Type" = "text/html;charset=utf-8";
Date = "Mon, 28 Apr 2014 19:01:43 GMT";
Server = "nginx admin";
} }, NSUnderlyingError=0x1096756e0 "Request failed: unacceptable content-type: text/html"}
It's weird, because the field EMAIL is:
NSLog(#" txtEmail.: %#",_txtEmail.text) = [2908:60b] txtEmail.: me#domain
But in the params of the AFN is changed to: me%40domain
Somebody knows why?
Thanks a lot!
That's probably because the # sign is encoded as %40, similarly to how a space is encoded as %20.
http://en.wikipedia.org/wiki/Percent-encoding
Related
I have a very basic HTTP Function:
exports.reporting = functions.https.onRequest(async (req,res) => {
cors(req, res, () => {
const text = req.query.text;
console.log(text);
return res.send(`Test Completed`);
});
});
When I call: curl "http://localhost:5001/<project-id>/us-central1/reporting"
It works fine:
StatusCode : 200
StatusDescription : OK
Content : Test Completed
RawContent : HTTP/1.1 200 OK
vary: Origin
connection: close
Content-Length: 14
Content-Type: text/html; charset=utf-8
Date: Wed, 20 Jan 2021 06:51:07 GMT
ETag: W/"e-NPX2Kiy1JwL0pK33NZe7NuviU84"
X-Powered-By...
Forms : {}
Headers : {[vary, Origin], [connection, close], [Content-Length, 14], [Content-Type, text/html;
charset=utf-8]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 14
But when I call: curl "http://localhost:5001/<project-id>/us-central1/reporting?text=abc123"
I get an error:
curl : The remote server returned an error: (400) Bad Request.
At line:1 char:1
+ curl "http://localhost:5001/<project-id>/us-central1/reporting?text=abc123"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The Emulator log shows the function times out?
i functions: Beginning execution of "reporting"
! functions: Your function timed out after ~60s. To configure this timeout, see
https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
> C:\Users\User\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:640
> throw new Error("Function timed out.");
> ^
>
> Error: Function timed out.
> at Timeout.setTimeout [as _onTimeout] (C:\Users\User\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:640:19)
> at ontimeout (timers.js:436:11)
> at tryOnTimeout (timers.js:300:5)
> at listOnTimeout (timers.js:263:5)
> at Timer.processTimers (timers.js:223:10)
Worth to mention the deployed function works fine with parameters.
When testing Firebase Functions that use a query string on the URL on the Emulator with the curl tool don't forget to add the slash '/' prior the query string (denoted by the question mark symbol '?') in a similar fashion to: http://localhost:5001/<project-id>/us-central1/reporting/?text=abc123.
I have a C# application that return a Json status when I call "http://host:port/app-status".
The response looks like:
{
"prtg":
{
"result": [
{
"channel": "DDS - ZDM - Konsistenzprüfung",
"value": "3",
"valuelookup": "prtg.RCLookup.DDS_ZDM_Check.BitField"
},
{
"channel": "ZDM DB Verbindungsversuche",
"value": "0",
"valuelookup": "prtg.RCLookup.Default.DB.Connect.Retry"
}
]
}
}
Then i have on zabbix server an item which type is http agent.
The request works fine. But I get this error:
Preprocessing failed for: HTTP/1.1 200 Ok..Content-Length: 361..Content-Type: application/json..Server: Grapevine/4.1.1.0 M...
1. Failed: cannot extract value from json by path ".prtg.result[0].value": cannot parse as a valid JSON object: invalid object format, expected opening character '{' or '[' at: 'HTTP/1.1 200 Ok
Content-Length: 361
Content-Type: application/json
Server: Grapevine/4.1.1.0 Microsoft-HTTPAPI/2.0
Date: Fri, 12 Apr 2019 14:19:12
In the preprocessing tab I have set a processing step with JsonPath.
The JsonPath is: .prtg.result[0].value
What is wrong?
Can help me everybody?
from error message it seems that you are trying to parse response from server inclusive headers which is wrong - you need to parse as JSON only data which is sent back (exclusive headers)
I am building an app using ionic/cordova that will take a scan, store this to the device (this part works), and also upload this data to a server (this part doesn't work).
The server is a RESTful api that expects JSON to be POSTed (I didn't create the server, these are the details I have been given).
When I try to post to the server I am getting the following error -
{status: 415, url: "http://jsfitnessservice.azurewebsites.net/api/values123", headers: {…}, error: ""} error:""
headers:
content-length:"0"
date:"Tue, 06 Feb 2018 19:41:36 GMT"
request-context:"appId=cid-v1:bf5436d9-7e1e-491e-b79d-d40d9b401307"
server:"Kestrel"
x-android-received-millis:"1517946100312"
x-android-response-source:"NETWORK 415"
x-android-selected-protocol:"http/1.1"
x-android-sent-millis:"1517946100070"
x-powered-by:"ASP.NET"
My code -
let httpData = {
"id": this.device.uuid,
"scanDateTimes": this.lastScans,
"appVersion": "Version 1.0"
}
let header = new Headers();
header.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('http://jsfitnessservice.azurewebsites.net/api/values 123', httpData, header).then
(data =>{
console.log("Data Status - ", data.status);
}).catch(error =>{
console.log("Error - ", error)
});
I have tried a few things that I have seen online, such as adding the header to an object, or using JSON.Stringify() around the data I am sending. But these give errors too.
JSON.stringify around data gives this error -
status: -1, error: "unsupported params type, needs to be a JSON object"
Making header an object gives this error -
status: 0, error: "advanced-http: header values must be strings", headers: {…}}
Have you tried using
this.http.setDataSerializer(‘json’)
this.http.post('http://jsfitnessservice.azurewebsites.net/api/values 123', httpData, {'Content-Type': 'application/json; charset=utf-8'}).then
(data =>{
console.log("Data Status - ", data.status);
}).catch(error =>{
console.log("Error - ", error)
});
I am constrained to using AFNetworking, but I am working in Swift. I am trying to retrieve data from a POST API request that is supposed to be returning JSON. However it seems that no matter how I make the request I am not able to see what is being returned and that it does not seem to be in proper JSON format. Here's what I've tried.
(1) The canonical approach:
manager.responseSerializer = AFJSONResponseSerializer.init(readingOptions: .AllowFragments)
manager.responseSerializer.acceptableContentTypes = serialiazationTypes
This produces the error: Invalid value around character 2
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 2." UserInfo={NSDebugDescription=Invalid value around character 2., NSUnderlyingError=0x60800004ad70 {Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x608000a2c140> { URL: https://API_ADDRESS} { status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2261;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 07 Dec 2016 15:46:26 GMT";
Server = "nginx/1.10.1";
} },
(2) Using the standard parser. So basically I removed any explicit setting of the response serializer, which produced this error:
Optional(Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={NSUnderlyingError=0x60000004ace0 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x61800082e6a0> { URL: https://API_ADDRESS } { status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2261;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 07 Dec 2016 15:49:12 GMT";
Server = "nginx/1.10.1";
(3) So then I tried to read as text/html, not requiring JSON, so that I could see what the problem is, but I don't seem to be able to retrieve this and just see what the content is either. So with this code:
manager.responseSerializer = AFHTTPResponseSerializer()
I ended up with this response, which does not even indicate why this is a bad request:
"Request failed: bad request (400)"
{ status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2261;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 07 Dec 2016 15:51:10 GMT";
Server = "nginx/1.10.1";
} }
Here are my questions
(1) In cases 1 & 2 above are these problems with parsing the response code whereas in case 3 I am just seeing the server tell me that my request is bad?
(2) How can I start figuring out why my request is bad? This is an internal API, but I'm not getting a lot of help with how it works. I have a sample curl command that does work with the API, but I'm not clear on how I am departing from it:
curl -X POST -v -s -H "Session-Token: EYYW$YW$YWYW" -H "Content-type: application/json" -d#sample.json https://API_ADDRESS
What is different between that and what I am doing below:
manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFHTTPResponseSerializer()
manager.requestSerializer.setValue(sessionToken, forHTTPHeaderField: tokenString)
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-type")
manager.POST(
user_url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation?,
responseObject: AnyObject!) in
print("JSON FROM POST: \(responseObject)")
},
failure: { (operation: AFHTTPRequestOperation?, error: NSError?) in
print("there was an error in POST: \(error)")
}
)
This error happens when the (Jackson, this case) JSON engine tries to parse some JSON that is not encoded in UTF-8.
How to tell the engine that it should expect something different from UTF-8, such as UTF-16?
HttpHeaders requestHeaders = createSomeHeader();
RestTemplate restTemplate = new RestTemplate();
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
String url = "someurl"
ResponseEntity<MyObject[]> arrayResponseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, MyObject[].class);
error log:
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream#44d397b0; line: 92, column: 42]; nested exception is org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream#44d397b0; line: 92, column: 42]
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:138)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:74)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:622)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:608)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:449)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:404)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:380)
... 4 more
Caused by: org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream#44d397b0; line: 92, column: 42]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1213)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:375)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2132)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2139)
at org.codehaus.jackson.impl.Utf8StreamParser._decodeUtf8_3fast(Utf8StreamParser.java:1962)
I got this exception when in the Java Client Application I was serializing a JSON like this
String json = mapper.writeValueAsString(contentBean);
and on the Server Side I was using Spring Boot as REST Endpoint.
Exception was:
nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xaa
My problem was, that I was not setting the correct encoding on the HTTP Client.
This solved my problem:
updateRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity entity= new StringEntity(json, "UTF-8");
updateRequest.setEntity(entity);
Android set content type HttpPost
JSON data must be encoded as UTF-8, UTF-16 or UTF-32. The JSON decoder can determine the encoding by examining the first four octets of the byte stream:
00 00 00 xx UTF-32BE
00 xx 00 xx UTF-16BE
xx 00 00 00 UTF-32LE
xx 00 xx 00 UTF-16LE
xx xx xx xx UTF-8
It sounds like the server is encoding data in some illegal encoding (ISO-8859-1, windows-1252, etc.)
I got this after saving the JSON file using Notepad2, so I had to open it with Notepad++ and then say "Convert to UTF-8". Then it worked.
On the off chance it may help others I'll share a related anecdote.
I encountered this exact error (Invalid UTF-8 middle byte 0x3f) running a PowerShell script via the PowerShell Integrated Script Environment (ISE). The identical script, executed outside the ISE, works fine. The code uses the Confluence v3 and v5.x REST APIs and this error is logged on the Confluence v5.x server - presumably because the ISE somehow mucks with the request.
This awnser solved my problem. Below is a copy of it:
Make sure to start you JVM with -Dfile.encoding=UTF-8. You JVM
defaults to the operating system charset
This is a JVM argument which could be added, for example, either to JBoss standalone or JBoss running from Eclipse.
In my case, this problem happened isolatelly on only one of my team people's computer. All the others was working without this problem.
I had this problem inconsistently between different platforms, as I got JSON as String from Mapper and did the writing myself. Sometimes it went into file as ansi and other times correctly as UTF8. I switched to
mapper.writeValue(file, data);
letting Mapper do the file operations, and it started working fine.
client text protocol
POST http://127.0.0.1/bom/create HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Postman-Token: 50ecfbfe-741f-4a2b-a3d3-cdf162ada27f
Host: 127.0.0.1
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 405
{
"fwoid": 1,
"list": [
{
"bomIndex": "10001",
"desc": "带GH 1.25 13pin 公座带针 白色",
"pn": "084.0001.0036",
"preUse": 1,
"type": "追觅 除螨仪-开关PCB组件"
},
{
"bomIndex": "10002",
"desc": "紫米音箱-商品码标签",
"pn": "Z.08.013.0051",
"preUse": 1,
"type": "E060A0302301"
}
]
}
HTTP/1.1 200 OK
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:23:42 GMT
Content-Length: 40
{"code":"0","message":"BOM保存成功"}
a springboot Controller code as below:
#PostMapping("/bom/create")
#ApiOperation(value = "保存BOM")
#BusinessOperation(module = "BOM",methods = "解析BOM")
public JsonResult save(#RequestBody BOMSaveQuery query)
{
return bomService.saveBomList(query);
}
when i debug on loopback interface,it works ok. while deploy on internet server via bat command, i got an error
ServletInvocableHandlerMethod - Could not resolve parameter [0] in public XXXController.save(com.h2.mes.query.BOMSaveQuery): JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])]
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - Completed 400 BAD_REQUEST
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}
add a jvm arguement works for me.
java -Dfile.encoding=UTF-8