Send POST and read streaming response

2019-09-19 08:31发布

问题:

I have a server that takes a POST request and answers with a data stream. I have seen that on URL I can open a connection or a stream. A stream, however, has no method for writing out data:

URL url = new URL("...");
url.openConnection(); //either I open a connection which has a output stream, but no input
url.openStream(); //or I open a stream, but I cannot write anything out

How can I solve this problem elegantly?

回答1:

Sample code snippet to use OutputStream.

Note: You can set content types & send some URL parameters to the URL only.

    URL obj = new URL(url);//some url
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    String urlParams = "fName=xyz&lname=ABC&pin=12345"; // some parameters
    wr.writeBytes(urlParams);
    wr.flush();
    wr.close();

Have a look at detailed explanation in this article1 and article2



标签: java http