You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GET请求查询字符串问题:q4方法返回值不符AutoLab预期

Fixing Your GET Request Parameter Issue

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() with addQueryParam(): This appends parameters to the URL in the standard ?key=value&key2=value2 format that GET requests expect.
  • Added error handling safeguards: If an IO exception occurs or the server returns an empty response, we return -1 to avoid crashing from NumberFormatException when 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:49:48