跳到正文
DEV Community· MinPin Proxy·· 1 小時前AI 評分59

如何找出 curl 成功、應用程式卻回傳 400 的原因:比對兩個「相同」請求

It works in curl and returns 400 from the app. Finding the difference between two "identical" requests.

AI 導讀

當 curl 成功而應用程式回傳 400、415 或 403,問題可能在網絡函式庫改動或省略請求內容,應比對實際送出的請求。文章建議透過除錯代理或平台網絡檢查器擷取標頭和原始請求內容,匯出成 curl 重試,再逐項修改標頭或本文欄位定位差異。常見差異包括 Content-Type、日期格式、缺失欄位、查詢字串編碼、重新導向及分塊傳輸;文章亦建議用固定 JSON 樣本測試日期、null 值及鍵名。

正文

MinPin Proxy

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:

  1. 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.
  2. Export it as a curl command and run that. If it fails the same way, the problem is in the request, not the app.
  3. 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 httpBody on a URLRequest and don't set Content-Type, the request goes out as application/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()) sends application/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 default dateEncodingStrategy is .deferredToDate, which writes a Date as 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 null properties by default, and kotlinx.serialization leaves out properties that still have their default value unless encodeDefaults = true. An API that requires the field to be present, even as null or 0, returns a validation error for a field the app "definitely sends".
  • Key names: a keyEncodingStrategy of .convertToSnakeCase, or a @SerializedName / @Json(name=) missing on one property, sends userId where the server expects user_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/... or okhttp/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 Authorization header when following a redirect to a different host. Other clients have their own rules. If the API redirects (http to https, 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 301 or 302 in reply to a POST is usually followed with a GET and no body. The server then sees a body-less GET on an endpoint that only takes POST.
  • Cookies: curl sends none unless told to. The app's cookie store may send an old session cookie that the server prefers over the Authorization header.

How the body is sent

  • Chunked uploads: if the body length isn't known up front (an input stream on iOS, a RequestBody with contentLength() of -1 on OkHttp), the request uses Transfer-Encoding: chunked instead of Content-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 URLSession fails the request on recent iOS versions. If the API was designed around a GET with 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, Accept and 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