java - 在java中调用没有正文的Post请求
问题描述
我有一个不接受任何输入的 post API。我必须从 API 获取输出。但它给出了编译错误。
HttpURLConnection connection = null;
String targetUrl="https://idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1/bots/"+BotID+"/dynamicEntities/"+dynamicEntityId+"/pushRequests
URL url = new URL(targetUrl);
connection=(HttpURLConnection) url.openConnection();
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic aWRjcy1vZGEtOTQxN2Y5MzU2MGI5NGViOGEyZTJhNGM5YWFjOWEzZmYtdDBfQVBQSUQ6MjQ0YWU4ZTItNmY3MS00YWYyLWI1Y2MtOTExMDg5MGQxNDU2");
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
**osw.write();** //this line is expecting input in parameter
osw.flush();
osw.close();
os.close();
connection.connect();
如果我没有在其中传递任何值,osw.write()
则会出现编译错误。我该如何解决。
解决方案
看下面的post调用方法。您需要将输出流添加到所需osw.write()
的参数中。
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
else {
System.out.println("POST request not worked");
}
}
有关上述代码的更多详细信息,请参见此处。
推荐阅读
- mysql - 备份 MySQL 数据库
- python - Docker setup for two apps
- magento - Magento 2 - Create html element with data-mage-init attribute - with Js/Jquery
- python - Python Kivy - 不使用 kv 语言更新属性
- docker - 如何在我的 Dockerfile 中从 docker-compose 访问已安装的 voume?
- c# - 如何使用 Xbim 为 IFC 对象创建和操作 Table 属性?
- python - 当使用“mlflow models serve”提供模型时如何处理 MLflow 中的错误?
- javascript - Javascript数组过滤和映射
- dart - 解析 base64 API 响应会引发 FormatException
- reactjs - 如何将多个 sagas 合并到 rootSaga 中?