|
| 1 | +package io.github.kimmking.gateway.outbound.httpclient; |
| 2 | + |
| 3 | +import io.netty.buffer.Unpooled; |
| 4 | +import io.netty.channel.ChannelHandlerContext; |
| 5 | +import io.netty.handler.codec.http.DefaultFullHttpResponse; |
| 6 | +import io.netty.handler.codec.http.FullHttpRequest; |
| 7 | +import io.netty.handler.codec.http.FullHttpResponse; |
| 8 | +import org.apache.http.HttpResponse; |
| 9 | +import org.apache.http.client.HttpClient; |
| 10 | +import org.apache.http.client.methods.HttpGet; |
| 11 | +import org.apache.http.impl.client.HttpClients; |
| 12 | +import org.apache.http.util.EntityUtils; |
| 13 | + |
| 14 | +import java.io.IOException; |
| 15 | + |
| 16 | +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; |
| 17 | +import static io.netty.handler.codec.http.HttpResponseStatus.OK; |
| 18 | +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; |
| 19 | + |
| 20 | +/** |
| 21 | + * @author isaac |
| 22 | + * @date 2020/11/2 |
| 23 | + */ |
| 24 | +public class HttpOutboundHandler { |
| 25 | + |
| 26 | + private String backendUrl; |
| 27 | + |
| 28 | + public HttpOutboundHandler( String serverUrl) { |
| 29 | + this.backendUrl = serverUrl.endsWith("/") ? serverUrl.substring(0,serverUrl.length()-1) : serverUrl; |
| 30 | + } |
| 31 | + |
| 32 | + public void handle( final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) throws IOException { |
| 33 | + final String url = this.backendUrl + fullRequest.uri(); |
| 34 | + fetchGet(fullRequest, ctx, url); |
| 35 | + |
| 36 | + } |
| 37 | + private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url){ |
| 38 | + final HttpGet httpGet = new HttpGet(url); |
| 39 | + HttpClient client = HttpClients.createDefault(); |
| 40 | + HttpResponse response = null; |
| 41 | + try { |
| 42 | + response = client.execute(httpGet); |
| 43 | + } catch (IOException e) { |
| 44 | + e.printStackTrace(); |
| 45 | + } |
| 46 | + handleResponse(inbound, ctx, response); |
| 47 | + } |
| 48 | + private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) { |
| 49 | + FullHttpResponse response = null; |
| 50 | + try { |
| 51 | + byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity()); |
| 52 | + System.out.println(new String(body)); |
| 53 | + |
| 54 | + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body)); |
| 55 | + } catch (Exception e) { |
| 56 | + e.printStackTrace(); |
| 57 | + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); |
| 58 | + } finally { |
| 59 | + if (fullRequest != null) { |
| 60 | + ctx.write(response); |
| 61 | + } |
| 62 | + ctx.flush(); |
| 63 | + ctx.close(); |
| 64 | + } |
| 65 | + |
| 66 | + } |
| 67 | +} |
| 68 | + |
0 commit comments