【问题标题】:Android can't send GET request with HttpURLConnectionAndroid 无法使用 HttpURLConnection 发送 GET 请求
【发布时间】:2010-10-21 08:57:20
【问题描述】:

我正在尝试在我的应用程序中使用 HttpURLConnection。我将请求方法设置为“GET”,但是当我尝试检索输出流时,该方法更改为“POST”! 我不确定是不是这个原因,但是当我使用“POST”发送请求时,我的 JSON 服务器(我使用 JAX-RS)会返回一个空白页面。

这是我的代码的 sn-p:

// Create the connection
HttpURLConnection con = (HttpURLConnection) new URL(getUrl() + uriP).openConnection();
// Add cookies if necessary
if (cookies != null) {
  for (String cookie : cookies) {
    con.addRequestProperty("Cookie", cookie);
    Log.d("JSONServer", "Added cookie: " + cookie);
  }
}
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestMethod("GET");
con.setConnectTimeout(20000);
// Add 'Accept' property in header otherwise JAX-RS/CXF will answer a XML stream
con.addRequestProperty("Accept", "application/json");

// Get the output stream
OutputStream os = con.getOutputStream();

// !!!!! HERE THE REQUEST METHOD HAS BEEN CHANGED !!!!!!
OutputStreamWriter wr = new OutputStreamWriter(os);
wr.write(requestP);
// Send the request
wr.flush();

谢谢你的回答。 埃里克

【问题讨论】:

    标签: android httpurlconnection


    【解决方案1】:

    但 GET 请求假定没有内容...通过写入连接输出流,您正在将请求的性质更改为 POST。该库非常有助于发现您正在执行此操作...the doc for getOutputStream 明确指出“调用此方法时,默认请求方法更改为“POST”。”

    如果您需要在 GET 中将数据发送到服务器,则需要以正常方式将其编码到 URL 参数中。

    【讨论】:

    • 太好了,它有效!非常感谢您的快速回答。我犯了一个错误:我重用了一个旧代码,它使用上面的 sn-p 请求服务器。此服务器不介意请求使用 POST 或 GET 方法!
    【解决方案2】:

    从您的代码中删除 con.setDoOutput(true);。 然后 Web 服务请求将与 GET 方法正常工作

    HttpURLConnection 默认使用 GET 方法。它将使用 POST 如果 setDoOutput(true) 已被调用。

    以上评论可在以下网址中找到

    Android HTTPURLConnection Class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多