0

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?

navige
  • 2,447
  • 3
  • 27
  • 53
  • 1
    Pretty good explaination here : http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests – GPI Sep 25 '15 at 09:46

1 Answers1

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

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • I would question the naming of the `urlParams` variable as its content is passed in the BODY of the HTTP request, and not in the URL itself. (The fact that you have to URL encode the parameters when POSTing a application/x-www-form-urlencoded request does not mean that those are URL parameters). – GPI Sep 28 '15 at 12:03