如何发送客户端可以使用HTTPURLConnection的inputStream读取的数据?

时间:2018-06-27 20:56:43

标签: java http

我接受HTTPURLConnection来处理POST请求。我想发送一个答复,客户可以通过httpURLConnection.getInputStream()阅读。即使我确实通过服务器上的ServerSocket实例打开的套接字发送数据,客户端甚至甚至在之前都无法读取。

客户

HttpURLConnection conn = (HttpURLConnection) url.openConnection();        
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept-Language", "UTF-8");
conn.setDoOutput(true);        
conn.setDoInput(true);
OutputStream outStrm = conn.getOutputStream();
outStrm.write(request.getPostContent());
outStrm.flush();
InputStream inStrm = conn.getInputStream();  // <--- blocks here. NOT on the read
InputStreamReader inStrmRdr = new InputStreamReader(inStrm);
BufferedReader bufRdr = new BufferedReader(inStrmRdr);
String s = bufRdr.readLine();

服务器

ServerSocket servSok = new ServerSocket(portNmb);
Socket sok = servSok.accept();
readStuff(sok.getInputStream());  // **reading from the client is fine**
OutputStream outStrm = sok.getOutputStream();
OutputStreamWriter outStrmWtr = new OutputStreamWriter(outStrm);
outStrmWtr.write("hello");
outStrmWtr.flush(); // <-- this SHOULD unblock the waiting client read?

我希望服务器将响应发送到连接的客户端。响应采用XML。

0 个答案:

没有答案