我想用GET方法发送HTTP请求,但我无法设置GET方法。 这是我的代码:
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("p1", "123")
.appendQueryParameter("p2", "123");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
Log.e("ERROR", conn.getResponseMessage());
Log.e("ERROR", conn.getRequestMethod());
Log.e("ERROR", String.valueOf(conn.getResponseCode()));
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
在代码中,我设置了GET方法,但在日志中,请求方法是POST:
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ Method Not Allowed
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ POST
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ 405
什么问题?
答案 0 :(得分:7)
问题是
conn.setDoOutput(true);
当设置为true时,请求方法更改为POST
,因为GET或DELETE不能有请求正文