java - 已连接:但没有输出
问题描述
URL url2 = new URL("https://win-artl-dev.my.com/rap/opu/odata/ACNLQD/ALPS_SRV/CourseSet");
HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection();
connection2.setDoOutput(true);
//connection2.setRequestMethod("POST");
OutputStream os = connection2.getOutputStream();
connection2.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection2.setRequestProperty("Accept", "application/json");
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
connection2.setRequestProperty("x-csrf-token", server);
osw.write("{\n" +
" \"Eid\": \""+content+"\",\n" +
" \"CourseId\": \""+content2+"\",\n" +
" \"ActId\": \""+content3+"\",\n" +
" \"PrgNme\": \""+content4+"\",\n" +
" \"Status\": \""+content7+"\",\n" +
" \"ChapterID\": \""+content5+"\",\n" +
" \"UnitID\": \""+content6+"\",\n" +
" \"Method\": \"GenerateNS\"\n" +
" } ");
osw.flush();
//connection2.connect();
osw.close();
os.close(); //don't forget to close the OutputStream
InputStream inputStream = connection2.getErrorStream();
if (inputStream == null)
inputStream = connection2.getInputStream();
// Read everything from our stream
BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String inputLine2;
StringBuffer response = new StringBuffer();
while ((inputLine2 = responseReader.readLine()) != null) {
response.append(inputLine2);
}
responseReader.close();
return response.toString();
我正在发送POST
上面给出的请求
- 带令牌
- 邮政
- 身体
我的问题是它一直说我已连接但没有返回任何输出。
java.lang.IllegalStateException:已连接
我想查看页面的输出或响应。
谁能建议我做错了什么?
解决方案
在获取输出流之前移动设置请求属性。当您获得输出流时,连接已打开,您会收到该异常。
//These two go above the getOutputStream()
connection2.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection2.setRequestProperty("Accept", "application/json");
OutputStream os = connection2.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
connection2.setRequestProperty("x-csrf-token", server);
那是那个例外:)我仍然不能保证你的代码会起作用
推荐阅读
- swift - 如何使单元格文本标签成为 Firestore 集合中文档中的特定字段?
- unreal-engine4 - 我在游戏中迷路了,我该如何回来?(虚幻引擎)
- codenameone - 退出表单时如何检测输入字段是否仍在编辑?
- html - 仅在Angular中使用*ngFor复制的div时如何设置默认单选选项?
- go - 循环异步进程
- jquery - jquery根据同一行中的另一个值添加每个属性
- stm32 - 如何在 STM32F205 上调试程序启动?
- css - ReactJS — 如何使用 createRef() 修改 CSS 属性?
- java - 无法在 Web 视图中加载 PDF 文件
- react-native - 如何更改投射图像上显示的标题文本字体和颜色