java - HttpUrlConnection“PUT”请求也发送“GET”请求
问题描述
我的问题是,当我使用向 myHttpURLConnection
发送请求时,它先发送请求,然后再发送请求。我想知道我必须发送请求的任何代码是否导致它也发送请求。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 - java多线程执行器从不关闭线程
- python - PyQt Signal位置参数消失
- flutter - 暂时禁用文本字段时保持键盘打开
- javascript - 单击时如何在新的浏览器选项卡中打开下载链接并在文件下载链接出现之前在该选项卡上设置倒计时
- azure - Azure 管道输出错误 CS0117:“Resource.Id”不包含“XXXid”的定义(Xamarin Android)
- java - GraphQL 错误:需要一个名为“FileUpload”的用户定义的 GraphQL 标量类型,但没有找到
- android - 如何使 Android 通知“持久”?
- c# - Asp Net Core (2.1) WebApp - API 和 Web 界面的身份验证
- react-native - Redux 远程开发工具:Chrome 检查器选项卡而不是单独的窗口
- sql - SQL:添加外键失败