gpt4 book ai didi

java - HttpUrlConnection "PUT"请求还发送 "GET"请求

转载 作者:行者123 更新时间:2023-12-02 02:00:25 25 4
gpt4 key购买 nike

我的问题是,当我使用 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;
}
}

最佳答案

OBJ.openStream(); 发送 GET 请求(请参阅 java.net.URL.openStream ),因为它打开一个输入流来读取该 URL 的内容。

关于java - HttpUrlConnection "PUT"请求还发送 "GET"请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51658366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com