我的问题是,当我使用HttpURLConnection
向我的PUT
发送REST API
请求时,它先发送GET
请求,然后发送PUT
请求。我想知道我必须发送PUT
请求的任何代码是否导致它也发送GET
请求。
我知道在我的Android
代码中会发生此问题,因为我也使用Postman
发送PUT
请求,但是我从来没有遇到问题。
下面是我用来发送HttpUrlConnection
请求的函数的副本。
public String HTTPConnection(String requestType, String url, String input, Context context, Activity activity){
HttpURLConnection connection = null;
try {
URL OBJ = new URL(url);
connection = (HttpURLConnection) OBJ.openConnection();
connection.setRequestMethod(requestType);
switch (requestType.toLowerCase()) {
case "get":
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
int i = 1;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
i++;
}
in.close();
return response.toString();
case "put":
if (!input.equals("")){
OBJ.openStream();
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
}
Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(input);
writer.flush();
writer.close();
connection.getInputStream();
return "";
default:
return "";
}
} catch (IOException e){
e.printStackTrace();
return null;
}
}