Created
May 14, 2015 22:45
-
-
Save zhong-j-yu/7fa4476019bd26a0e4b2 to your computer and use it in GitHub Desktop.
simple demo of proxy, log response bodies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package _bayou; | |
import bayou.bytes.ByteSource; | |
import bayou.http.*; | |
import bayou.util.End; | |
import java.nio.ByteBuffer; | |
// simple demo of proxy, log response bodies | |
public class HttpProxyX | |
{ | |
public static void main(String[] args) throws Exception | |
{ | |
int port = 9090; | |
HttpClient downstream = new HttpClient(); | |
HttpHandler handler = request-> | |
{ | |
if(request.method().equals("CONNECT")) | |
{ | |
return HttpResponse.text(200, "tunneling request granted"); | |
} | |
else | |
{ | |
return downstream.send0(request, null) | |
.then(HttpResponse::cache); | |
} | |
}; | |
HttpServer proxy = new HttpServer(handler); | |
proxy.conf() | |
.port(port) | |
.setProxyDefaults() | |
.accessLogger( access->logAccess(access) ) | |
; | |
proxy.start(); | |
System.out.printf("Bayou Demo HTTP+HTTPS Proxy, port = %s %n", port); | |
} | |
static void logAccess(HttpAccess access) | |
{ | |
System.out.println("--------------------------------------------------------"); | |
HttpRequest request = access.request; | |
System.out.println("REQUEST: "+request.method()+" "+request.absoluteUri()); | |
HttpResponse response = access.response; | |
System.out.println("RESPONSE: "+response.status()); | |
if(response.entity()==null) | |
System.out.println("NO BODY"); | |
else | |
printBody(response.entity()); | |
} | |
static void printBody(HttpEntity entity) | |
{ | |
System.out.println("BODY TYPE: "+entity.contentType()); | |
ByteSource body = entity.body(); | |
try | |
{ | |
while(true) | |
{ | |
ByteBuffer bb = body.read().sync(); // async -> sync ! | |
System.out.println(bb); // not actual content, just ByteBuffer.toString() | |
} | |
} | |
catch (End e) | |
{ | |
System.out.println("BODY EOF"); | |
} | |
catch (Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment