Android无法使用HttpURLConnection发送GET请求

我正在尝试在我的应用程序中使用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();

谢谢你的回答.
埃里克

解决方法:

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

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

上一篇:java – ClassCastException断开与PowerMockito的URLConnection连接的HttpURLConnection


下一篇:android – HttpURLConnection.getInputStream很慢