我正在尝试POST到某个端点,当GET方法不允许该URL时。使用HTTPURLConnection时,我将请求方法设置为post,并将doOutput设置为true。
但是出于某种原因,当我在InputStream上放置一个断点(由于文件丢失而导致失败)时,请求方法是GET,doOutput是false(只有doInput为true)。这导致404,方法不允许 找不到,说没有方法[get]的匹配处理程序。为什么它忽略了我的设置并继续进行,好像我什么都没输?
String result = null;
try {
HttpURLConnection connection = (HttpURLConnection)new URL(baseUrl + getTokenPath).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((clientid + ":" + secret).getBytes()));
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes ("grant_type=client_credentials");
wr.flush ();
wr.close ();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
result = response.toString();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
在您阅读DataOutputStream
的所有数据之前,请勿关闭InputStream
。
wr.close ();
关闭流会导致您断开连接。刷新足以发送POST
请求。
wr.flush ();