如何使用服务器管理请求 - 响应对话框的循环

时间:2012-01-03 06:48:20

标签: java http stream client-server

我正在编写一个简单的客户端 - 服务器系统,问题是:如何构建我的客户端代码以使POST请求响应在循环中工作?

目前它看起来像这样(现在它不是一个循环):

  1. 打开HttpURLConnection
  2. 设置属性
  3. setDoOutput(true)
  4. 写入输出流
  5. 关闭输出流
  6. new DataInputStream
  7. 阅读回复
  8. 退出方法
  9. 我不确定在下一次迭代中我需要保存哪些对象以及应该关闭哪些对象。

2 个答案:

答案 0 :(得分:1)

您需要保存连接对象,并且应该使用setDoInput(true)来阅读数据,但如果您只想阅读responseCoderesponseMessage,则不需要InputStream 。检查下面的代码。

HttpURLConnection connection =(HttpURLConnection)new URL("url").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "text/xml"); // depend on you
connection.setRequestProperty("Accept", "text/xml, application/xml"); // depend on you
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(yaml);
writer.close();
int statusCode = connection.getResponseCode();
String message = connection.getResponseMessage();

代表InputStreamReader

connection.setDoInput(true);
InputStreamReader reader =  new InputStreamReader(connection.getInputStream());
char[] cbuf = new char[100];
reader.read(cbuf); 
// there are 3 read method you can choose as per your convenience 
//and put a check for end of line in while loop for reading whole content. 
reader.close();

答案 1 :(得分:1)

在管理我自己关于这个主题的'研究'之后(感谢Google和诺基亚论坛论坛),我已经看到了我的代码的最终视图。这是一个文件上传循环:

path = Paths.get(requestString);
in = Files.newInputStream(path);

int i = 0;
while ((bytesRead = in.read(buf)) != -1) { 
    URL u = new URL(defaultURL);
    huc = 
        (HttpURLConnection) u.openConnection();
    huc.setRequestMethod("POST");
    huc.setDoOutput(true);
    huc.setDoInput(true);

    os = huc.getOutputStream();
    os.write(buf, 0, bytesRead);
    os.flush();
    os = null;

    // thanks to dku.rajkumar for the following block of code ! 
    InputStreamReader reader =  
        new InputStreamReader(huc.getInputStream());
    char[] cbuf = new char[400];
    reader.read(cbuf);
    reader.close();

    String s = new String(cbuf);
    messagebuffer.append(s + "\n\n");

    huc.disconnect();

    Thread.sleep(16);
}