在Java中以字符串形式发布XML,何时刷新和关闭连接?

在Java中以字符串形式发布XML,何时刷新和关闭连接?,java,Java,如果我有这段代码: StringBuilder postData = new StringBuilder(); postData.append(URLEncoder.encode(cxmlContent, "UTF-8")); byte[] postDataBytes = postData.toString().getBytes("UTF-8"); URL url = new URL(urlString); URLConnection con = url.openConnection(); /

如果我有这段代码:

StringBuilder postData = new StringBuilder();
postData.append(URLEncoder.encode(cxmlContent, "UTF-8"));
byte[] postDataBytes = postData.toString().getBytes("UTF-8");

URL url = new URL(urlString);
URLConnection con = url.openConnection();
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setConnectTimeout(20000);  // long timeout, but not infinite
con.setReadTimeout(20000);
con.setUseCaches(false);
con.setDefaultUseCaches(false);
// tell the web server what we are sending
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8" );
con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));

con.getOutputStream().write(postDataBytes);

// reading the response
InputStreamReader reader = new InputStreamReader(con.getInputStream());
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf )))
{
    buf.append( cbuf, 0, num );
}
String result = buf.toString();
那么,我是否仍需要使用:

con.getOutputStream().flush();
con.getOutputStream().close();
因为如果我在inputreader之前使用flush和close,那么我将不会收到任何输入。但如果我在代码末尾使用inputreader下面的flush和close,则会出现以下错误:

java.net.ProtocolException:读取输入后无法写入输出

Close()
打电话给 冲洗法也一样。 所以你实际上只需要给close打个电话,因为它们是多余的。 您没有收到数据,因为您对连接流应用了关闭。 我建议使用从流创建的Outputstreamwriter和Bufferedwriter

大概是这样的:

    OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); 
out.write("string=" + stringToReverse);
 out.close(); 
BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); 
String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close();

刷新为了确保数据离开缓冲区,在完全完成之前不要关闭流。不相关,但是为什么要对XML文档进行URL编码?