Replicate Curl unix-socket command in Java

旧时模样 提交于 2019-12-11 10:46:16

问题


I want to get the same string standard outputted by curl when I type something like:

curl --unix-socket file.sock http://path/to/rest/request

In my Java code. I figured out I need to use AFUNIXSocket, but I can set just the socket file on connection, so I suppose I have to manage my http connection manually.

Is there a way to make it easier? How do I start an http connection through the socket I create?


回答1:


So, I tried to manage the http connection by myself, it works but Im still looking for a cleaner way to do that. That's how I did:

AFUNIXSocket s = AFUNIXSocket.newInstance();
AFUNIXSocketAddress sockAdd = new AFUNIXSocketAddress(new File("file.sock"));

s.connect(sockAdd);

BufferedReader bf = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream());


pw.write("GET /to/rest/request HTTP/1.1\r\n");

pw.write("Host: path\r\n");
pw.write("Accept:*/*\r\n");
pw.write("\r\n");
pw.flush();
String reply = "";

Thread.sleep(500);
while (bf.ready())
   reply = reply + bf.readLine() + "\n";

That is the same to do a curl call like that:

curl --unix-socket file.sock http://path/to/rest/request


来源:https://stackoverflow.com/questions/49551526/replicate-curl-unix-socket-command-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!