自定义简单的Feign客户端

Feign客户端默认使用HttpURLConnection连接HTTP服务。

Feign框架的Request对象转换为HttpClientRequest对象,然后用httpclient.execute(httpRequest),返回一个HttpResponse对象,然后转为Feign框架的Response对象返回。

它可以请求最基础的http服务,并没有转换请求头,只能请求字符串,不能请求其他格式的服务。

public class MyClient implements Client {
	public Response execute(Request request, Options options) throws IOException {
		System.out.println("this is my client");
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			final String method = request.method();
			HttpRequestBase httpRequest = new HttpRequestBase() {
				public String getMethod() {
					return method;
				}
			};
			httpRequest.setURI(new URI(request.url()));
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			byte[] body = EntityUtils.toByteArray(httpResponse.getEntity());
			Response response = Response.builder().body(body).headers(new HashMap<String, Collection<String>>())
					.status(httpResponse.getStatusLine().getStatusCode()).build();
			return response;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
public class MyClientTest {

	public static void main(String[] args) {
		HelloClient client=Feign.builder()
				.client(new MyClient())
				.target(HelloClient.class,
						"http://localhost:8083");
		String result=client.hello();
		System.out.println(result);
	}

}
发布了254 篇原创文章 · 获赞 18 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36594703/article/details/82684230
今日推荐