RestAssured通过变量传递Token报File Not Found错误求助
Let's break down why you're hitting a "File Not Found" error when passing your Token via a variable, but it works perfectly with hardcoding. Here are the most likely causes and actionable fixes to check:
1. Your sessionKey might be null or invalid
The error could stem directly from GbPortalLogin.getSessionKey() failing to return a valid session key. If sessionKey is null, your concatenated token becomes Token null—an invalid authorization value. Many servers respond with 404 (instead of the more intuitive 401 Unauthorized) when they can't validate credentials, to avoid exposing that the resource exists.
How to verify & fix:
- Add a debug line to inspect the raw
sessionKeyvalue before building the token:String sessionKey = GbPortalLogin.getSessionKey(); System.out.println("Raw sessionKey: '" + sessionKey + "'"); // Quotes help spot hidden whitespace - If
sessionKeyis null/empty, debug theGbPortalLogin.getSessionKey()method. The "File Not Found" hint suggests this method might be failing to read a required file during session key retrieval—check for unhandled file I/O errors there.
2. Hidden whitespace or invalid characters in sessionKey
Sometimes the session key might include leading/trailing spaces, newlines, or special characters that break the Authorization header format when concatenated. Hardcoding avoids this because you're using a clean, known value.
Quick fixes:
- Trim the session key to remove extra whitespace before creating the token:
String token = "Token " + sessionKey.trim(); - Sanitize the key to remove non-printable or invalid characters (common if the key is read from a file with leftover newlines):
String cleanSessionKey = sessionKey.replaceAll("[^a-zA-Z0-9-_]", ""); String token = "Token " + cleanSessionKey;
3. RestAssured header resolution quirk
In rare cases, RestAssured might not resolve the variable correctly when building the request. Try using a dynamic header supplier to ensure the token value is evaluated at request execution time:
given() .header("Content-Type","application/json") .header("Authorization", () -> token) // Lambda ensures dynamic value resolution .body(pal.createIndentPayload())
4. Quick isolation test
To confirm the issue is with the token variable, copy the exact output from your System.out.println(token) and hardcode it into the header. For example, if your debug print shows Token abc12xyz, use:
.header("Authorization","Token abc12xyz")
If this works, the problem is definitely with how sessionKey is being retrieved or processed. If it still fails, the issue might be unrelated to the token (though this is unlikely given your original hardcoding success).
内容的提问来源于stack exchange,提问作者Pavan

