Plain HTTP Request to UrlConnection (Java)

Viewed 83

Make a request from request stream

I've an OutputStream contains the below Request. It's dynamic and everything(Method, Type, Data[Multipart/Non-Multipart/File]) can change. I just want A Response Stream from that Request.

POST /page.php HTTP/1.1
Host: example.com
User-Agent: Mozilla(Webkit) 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: en-gb,en;q=0.5 
Accept-Encoding: gzip, deflate 
Connection: keep-alive
Content-Type: multipart/form-data; boundary=myboundary 
 --myboundary

Content-Disposition: form-data; name="a" 1 
--myboundary

Content-Disposition: form-data; name="b" 2 
 --myboundary--

Building UrlConnection by hand is hard

I know I can make a UrlConnection by hand but that seems to be hard. To create it I need to add headers, data-values which I'll need to get by RegEx operation. I'm not getting how I would get multipart data by RegEx.

So, this approach is going to be hard also the request isn't always contains only String because sometimes it sends Files too. Also, I don't know much about Http format and I'm not confident.

So, I'm looking for a library or method or easy way to make a Request from above Stream and get the Response Stream.

Very simply : Sending a Request with those values(OutputStream) and getting response in InputStream.

1 Answers

We can send Request and get Response by using Socket.

We can create a new Socket and connect it with host and port. In the OutputStream we can input the plain request. We can get Response by Socket.getInputStream().


Request : Socket.getOutputStream() Response : Socket.getInputStream()

But, we'll have to connect to the Server with Socket.connect().

Socket sock = new Socket();
sock.connect(host, port);
DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
dos.write(reqStr.getBytes());
dos.flush();
dos.close();
DataInputStream dis = new DataInputStream(sock.getInputStream());
//Here dis is the response.
Related