问题
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