【问题标题】:Response code 400 OKHTTP响应码 400 OKHTTP
【发布时间】:2025-12-23 16:05:11
【问题描述】:

当我运行我的 android 应用程序时,我得到一个 响应代码 = 400,但是当我在浏览器和邮递员中测试相同的 URL 时,它的响应代码为 200。我做错了什么。这是get Request方法

  public static String getRequest(String myUrl) throws IOException {

        InputStream is = null;

        try {

            URL url = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(30000 /*milliseconds*/);
            conn.setConnectTimeout(20000 /*milliseconds*/);
            conn.setRequestMethod("GET");

            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            if (response != HttpURLConnection.HTTP_OK)
                is = conn.getErrorStream();
            else
            is = conn.getInputStream();

            Log.i(TAG, String.valueOf(response));


            // Convert the InputStream into a string
            return readStream(is);

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

我需要帮助。

【问题讨论】:

  • 你使用本地服务?
  • 不,我正在使用在线服务器
  • 错误 400 它的错误请求,检查你的值
  • 您的 url 中是否有任何 Queryparam 或邮递员请求中是否有特殊的 HTTP 标头
  • 代码是否适用于其他 URL?

标签: java android okhttp


【解决方案1】:

你不需要打电话:

conn.setRequestMethod("GET");
conn.setDoInput(true)

用于 GET 请求。我认为您缺少一些标题,例如(授权)

【讨论】:

  • 他得到了 400,这是错误的请求而不是未经授权的 401。
  • 当我为任何 url 执行 GET 时它工作正常,但是当我尝试使用 oData 过滤器查询执行 GET 时,它给了我错误 400 。这是给我错误 400 "housenaija.azurewebsites.net/api/PropertyListings?$filter=Price ge "+ minPrice+" 和 Price le "+maxPrice: 我将提供 minPrice 和 maxPrice 值的 url。
【解决方案2】:

所以我发现了问题,因为我使用 OData 过滤器进行查询,而真实设备设备无法编码这样的 URL,我不得不手动编码我的 URL。

这是我之前传入的:

   String url = *Const.HOUSE_URL+"PropertyListings?$filter=Price ge "+ minPrice+" and Price le "+maxPrice*

但编码时:String url = *Const.HOUSE_URL+"PropertyListings?$filter="+ **query** + minPrice+ **query1** + maxPrice;*

在哪里

String query = URLEncoder.encode("Price ge ", "utf-8");

String query1 = URLEncoder.encode(" and Price le ","utf-8");

那么传入我的 HTTP GET 请求的最终 url 是:

 String url = Const.HOUSE_URL+"PropertyListings?$filter="+ query + minPrice+ query1 + maxPrice;

其中 minPrice 和 maxPrice 是来自 EditText 的字符串值。

希望这对某人有所帮助。

【讨论】: