如何找出 curl 成功、應用程式卻回傳 400 的原因:比對兩個「相同」請求
It works in curl and returns 400 from the app. Finding the difference between two "identical" requests.
當 curl 成功而應用程式回傳 400、415 或 403,問題可能在網絡函式庫改動或省略請求內容,應比對實際送出的請求。文章建議透過除錯代理或平台網絡檢查器擷取標頭和原始請求內容,匯出成 curl 重試,再逐項修改標頭或本文欄位定位差異。常見差異包括 Content-Type、日期格式、缺失欄位、查詢字串編碼、重新導向及分塊傳輸;文章亦建議用固定 JSON 樣本測試日期、null 值及鍵名。
The bug: the backend developer runs the request with curl and gets a 200. The app sends "the same request" and gets a 400, or a 415, or a 403 from something in front of the server. Everyone agrees the requests are identical. They aren't. The networking library added, changed or dropped something on the way out.
Here's where the differences usually are, and how to find them without guessing.
Step one: compare the real requests
Don't compare the app's code with the curl command. Compare what was actually sent:
- Capture the app's request on the wire (a debugging proxy, or the platform's network inspector), including all headers and the exact body bytes.
- Export it as a curl command and run that. If it fails the same way, the problem is in the request, not the app.
- Remove or change one header (or one body field) at a time until it succeeds. The last thing you changed is the cause.
This takes ten minutes and replaces most of the arguing. The usual suspects below tell you where to look first.
Content-Type
-
iOS: if you set
httpBodyon aURLRequestand don't setContent-Type, the request goes out asapplication/x-www-form-urlencoded. A JSON body with that header gets a 400 or 415 from servers that check, or gets parsed as an empty form by frameworks that don't. -
OkHttp:
"...".toRequestBody("application/json".toMediaType())sendsapplication/json; charset=utf-8, because OkHttp adds the charset when the media type has none. Most servers accept it. A few strict ones or hand-written checks compare the whole header string and don't.
The JSON body isn't what you think
-
Swift dates:
JSONEncoder's defaultdateEncodingStrategyis.deferredToDate, which writes aDateas a number of seconds since January 1, 2001, not since 1970 and not as ISO 8601. A server that reads it as Unix time gets a date about 31 years too early, and a stricter one rejects the field. Set.iso8601(or whatever the API expects) on the encoder. -
Missing fields: Gson and Moshi leave out
nullproperties by default, and kotlinx.serialization leaves out properties that still have their default value unlessencodeDefaults = true. An API that requires the field to be present, even asnullor0, returns a validation error for a field the app "definitely sends". -
Key names: a
keyEncodingStrategyof.convertToSnakeCase, or a@SerializedName/@Json(name=)missing on one property, sendsuserIdwhere the server expectsuser_id.
The query string
URLComponents with URLQueryItem doesn't percent-encode +. Many servers decode + in a query string as a space, so email=a+b@example.com arrives as a b@example.com. Encode + as %2B yourself for those values. On Android, check how your builder encodes spaces versus + for the same reason.
Headers the library adds or removes
-
User-Agent: the app sends something like
MyApp/1.0 CFNetwork/... Darwin/...orokhttp/4.x. Some WAF and bot-protection rules block or challenge default library user agents, and the 403 comes from the edge, not your server. The response body (often HTML in a JSON API) is the hint. -
Authorization after a redirect: OkHttp drops the
Authorizationheader when following a redirect to a different host. Other clients have their own rules. If the API redirects (httptohttps, a missing trailing slash, an old domain), the second request may go out without credentials and fail with a 401 that the first request never got. -
Redirects and methods: a
301or302in reply to aPOSTis usually followed with aGETand no body. The server then sees a body-lessGETon an endpoint that only takesPOST. -
Cookies: curl sends none unless told to. The app's cookie store may send an old session cookie that the server prefers over the
Authorizationheader.
How the body is sent
-
Chunked uploads: if the body length isn't known up front (an input stream on iOS, a
RequestBodywithcontentLength()of-1on OkHttp), the request usesTransfer-Encoding: chunkedinstead ofContent-Length. Some proxies, gateways and older servers reject chunked request bodies or treat them as empty. -
GET with a body: OkHttp refuses to build it, and
URLSessionfails the request on recent iOS versions. If the API was designed around aGETwith a JSON body because curl allows it, the mobile client can't send it.
Making it not happen again
- Write a test that encodes each request model and compares the JSON to a fixture the backend agrees with, including dates, nulls and key names.
- Set
Content-Type,Acceptand the date strategy in one place (one encoder, one interceptor), not per call. - Log the method, URL, status and a request ID for failed requests in debug builds, so the next "works in curl" report starts with the real request.
This article was created with the help of AI.
來源:DEV Community · dev.to