我正在使用HttpUrlConnection,我想将请求方法更改为put
,这是代码:
uri = new URL(url);
con = (HttpURLConnection) uri.openConnection();
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
//con.setRequestProperty("Accept-Encoding", "Your Encoding");
con.setRequestProperty("Authorization", authCode);
con.setRequestProperty("Content-Type", contentType);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod(type);
但是当我调试项目时,方法是GET
我必须做什么,所以我可以将其设置为PUT
答案 0 :(得分:1)
URL url = null;
try {
url = new URL("http://localhost:8080/putservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write("hello");
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpsURLConnection != null) {
httpsURLConnection.disconnect();
}
}