如何在写入或读取DataStream后关闭HttpsURLConnectios

时间:2016-08-15 14:09:16

标签: java http url httpconnection bufferedinputstream

如何在Java中执行以下操作后才能使连接保持活动状态:

private static void makePostRequestAndPrintContent(String payload) throws IOException, InterruptedException{
    URL url = new URL("url");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setInstanceFollowRedirects(true);
    con.setRequestMethod("POST");   
    try( DataOutputStream wr = new DataOutputStream(con.getOutputStream())){
        wr.write(convertPayloadToBytes(payload));
    }

    printContent(con);

}

printcontent():

private static void printContent(HttpsURLConnection con) throws InterruptedException{

    if(con!=null){
    try {
       System.out.println("****** Content of the URL ********");
       String input;
       BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
       while ((input = br.readLine()) != null){
          System.out.println(input);     
       } 
       br.close();
    } catch (IOException e) {
            e.printStackTrace();
    }

在发布有效负载之后,我必须等待一段时间来从服务器进行PUT响应,但在执行后请求并从重定向站点读取内容后,连接将立即关闭(至少应用程序将被终止) 。 如何设置连接以等待进一步的响应,然后再次读取InputStream?

0 个答案:

没有答案