简体   繁体   English

对 UrlConnection 的普通 HTTP 请求 (Java)

[英]Plain HTTP Request to UrlConnection (Java)

Make a request from request stream从请求流发出请求

I've an OutputStream contains the below Request .我有一个OutputStream包含以下Request It's dynamic and everything( Method , Type , Data [Multipart/Non-Multipart/File]) can change.它是动态的,一切( MethodTypeData [Multipart/Non-Multipart/File])都可以改变。 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手动构建 UrlConnection 很难

I know I can make a UrlConnection by hand but that seems to be hard.我知道我可以手动创建UrlConnection但这似乎很难。 To create it I need to add headers , data-values which I'll need to get by RegEx operation.要创建它,我需要添加headers ,我需要通过RegEx操作获取的data-values I'm not getting how I would get multipart data by RegEx .我不知道如何通过RegEx获取多部分数据。

So, this approach is going to be hard also the request isn't always contains only String because sometimes it sends Files too .所以,这种方法会很困难,而且请求并不总是只包含String因为有时也会发送Files Also, I don't know much about Http format and I'm not confident.另外,我对Http格式不太了解,我没有信心。

So, I'm looking for a library or method or easy way to make a Request from above Stream and get the Response Stream .所以,我正在寻找一个库或方法或简单的方法来从上面的Stream发出Request并获取Response Stream

Very simply : Sending a Request with those values(OutputStream) and getting response in InputStream.非常简单:使用这些值(OutputStream)发送请求并在 InputStream 中获得响应。

We can send Request and get Response by using Socket .我们可以使用Socket发送Request并获取Response

We can create a new Socket and connect it with host and port.我们可以创建一个新的Socket并将其与主机和端口连接。 In the OutputStream we can input the plain request .OutputStream 中,我们可以输入普通的 request We can get Response by Socket.getInputStream() .我们可以通过Socket.getInputStream()获得Response


Request : Socket.getOutputStream() Response : Socket.getInputStream()请求Socket.getOutputStream()响应Socket.getInputStream()

But, we'll have to connect to the Server with Socket.connect() .但是,我们必须使用Socket.connect()连接到Server

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM