首页 > 解决方案 > 已连接:但没有输出

问题描述

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:已连接

我想查看页面的输出或响应。

谁能建议我做错了什么?

标签: javaeclipseurlpostoutputstream

解决方案


在获取输出流之前移动设置请求属性。当您获得输出流时,连接已打开,您会收到该异常。

                //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);

那是那个例外:)我仍然不能保证你的代码会起作用


推荐阅读