GET请求查询字符串问题:q4方法返回值不符AutoLab预期
Hey there, I can see you've already pinpointed the root cause of your issue—you're sending GET request query parameters as HTTP headers instead of appending them to the URL's query string. That's why the server isn't recognizing your parameters and returning an unexpected response.
What Went Wrong with Your Code
In GET requests, parameters like powerful=23 need to be part of the URL's query string (e.g., https://example.com/api?key=value&another=foo), not included in the HTTP request headers. Your code uses setHeader() to stuff these values into headers, so the server never finds the data it needs to process your request correctly.
Corrected Code
We'll use Apache HttpClient's addQueryParam() method to properly attach the parameters to the query string instead:
import org.apache.http.client.fluent.Request; import java.io.IOException; public static int q4(int n) { String url = "https://fury.cse.buffalo.edu/ps-api/type-two"; String response = ""; try { response = Request.Get(url) .addQueryParam("powerful", "23") // Add as query param, not header .addQueryParam("silver", "56") .addQueryParam("input", String.valueOf(n)) .execute().returnContent().asString(); } catch (IOException ex) { ex.printStackTrace(); return -1; // Return fallback value on error to avoid parse failures } // Guard against empty responses to prevent NumberFormatException if (response.isEmpty()) { return -1; } return Integer.parseInt(response); }
Key Improvements
- Replaced
setHeader()withaddQueryParam(): This appends parameters to the URL in the standard?key=value&key2=value2format that GET requests expect. - Added error handling safeguards: If an IO exception occurs or the server returns an empty response, we return
-1to avoid crashing fromNumberFormatExceptionwhen parsing an empty string.
With these changes, when you pass input 2, your request will send all required parameters correctly, and the server should return the expected 548 response.
内容的提问来源于stack exchange,提问作者jhonathan

