3

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

这是我的代码片段:

// 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();

谢谢你的回答。埃里克

4

2 回答 2

8

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

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

于 2010-10-21T09:07:51.033 回答
4

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

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

上面的评论可以在下面的 URL 中找到

Android HTTPURLConnection 类

于 2015-02-27T12:21:13.107 回答