最近要在非SpringBoot环境调用OpenFeign接口, 需要用到httpclient, 注意到现在 HttpClient 版本已经到 5.2.1 了. 之前在版本4中的一些方法已经变成 deprecated, 于是将之前的工具类升级一下, 顺便把中间遇到的问题记录一下
首先参考Apache官方的快速开始 httpcomponents-client-5.2.x quickstart, 这是页面上给的例子
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
}
}
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
}
}
上面的例子可以正常运行, 但是在HttpClient5中, CloseableHttpResponse execute(ClassicHttpRequest request) 这个方法已经被标记为 Deprecated
@Deprecated
HttpResponse execute(ClassicHttpRequest var1) throws IOException;
@Deprecated
HttpResponse execute(ClassicHttpRequest var1, HttpContext var2) throws IOException;
@Deprecated
ClassicHttpResponse execute(HttpHost var1, ClassicHttpRequest var2) throws IOException;
@Deprecated
HttpResponse execute(HttpHost var1, ClassicHttpRequest var2, HttpContext var3) throws IOException;
取而代之的, 是这四个带 HttpClientResponseHandler 参数的 execute 方法
<T> T execute(ClassicHttpRequest var1, HttpClientResponseHandler<? extends T> var2) throws IOException;
<T> T execute(ClassicHttpRequest var1, HttpContext var2, HttpClientResponseHandler<? extends T> var3) throws IOException;
<T> T execute(HttpHost var1, ClassicHttpRequest var2, HttpClientResponseHandler<? extends T> var3) throws IOException;
<T> T execute(HttpHost var1, ClassicHttpRequest var2, HttpContext var3, HttpClientResponseHandler<? extends T> var4) throws IOException;
}
这个 HttpClientResponseHandler 作为响应的处理方法, 里面只有一个接口方法(要注意到这是一个函数式接口)
@FunctionalInterface
public interface HttpClientResponseHandler<T> {
T handleResponse(ClassicHttpResponse var1) throws HttpException, IOException;
}
JDK中提供了一个默认的实现, BasicHttpClientResponseHandler(基于 AbstractHttpClientResponseHandler)
public abstract class AbstractHttpClientResponseHandler<T> implements HttpClientResponseHandler<T> {
public AbstractHttpClientResponseHandler() {
}
public T handleResponse(ClassicHttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (response.getCode() >= 300) {
EntityUtils.consume(entity);
throw new HttpResponseException(response.getCode(), response.getReasonPhrase());
} else {
return entity == null ? null : this.handleEntity(entity);
}
}
public abstract T handleEntity(HttpEntity var1) throws IOException;
}
public class BasicHttpClientResponseHandler extends AbstractHttpClientResponseHandler<String> {
public BasicHttpClientResponseHandler() {
}
public String handleEntity(HttpEntity entity) throws IOException {
try {
return EntityUtils.toString(entity);
} catch (ParseException var3) {
throw new ClientProtocolException(var3);
}
}
public String handleResponse(ClassicHttpResponse response) throws IOException {
return (String)super.handleResponse(response);
}
}
这样基础的使用方式就改为了下面的形式
public static void main(final String[] args) throws Exception {
final CloseableHttpClient httpClient = HttpClients.createDefault();
try (httpClient) {
final HttpGet httpGet = new HttpGet("https://www.baidu.com/home/other/data/weatherInfo");
final String responseBody = httpClient.execute(httpGet, new BasicHttpClientResponseHandler());
System.out.println(responseBody);
}
}
可以看到, 上面的 BasicHttpClientResponseHandler 是一个比较简单的实现, 大于300的响应状态码直接抛出异常, 其它的读出字符串. 这样的处理方式对于更精细的使用场景是不够的
之前在 HttpClient4 时, 可以通过CloseableHttpResponse response = client.execute(httpRequest), 对 response 进行判断, 现在response已经完全被handler 包裹, 需要通过自定义函数式方法处理响应, 看下面的例子
首先定义一个响应结果类, 数据部分使用泛型
@Data
public class Client5Resp<T> implements Serializable {
private int code;
private String raw;
private T data;
public Client5Resp(int code, String raw, T data) {
this.code = code;
this.raw = raw;
this.data = data;
}
}
然后对响应结果自定义 handler, 因为是函数式接口, 所以很方便在方法中直接定义, 处理的逻辑是:
private static <T> Client5Resp<T> httpRequest(
TypeReference<T> tp,
HttpUriRequest httpRequest) {
try (CloseableHttpClient client = HttpClients.createDefault()) {
Client5Resp<T> resp = client.execute(httpRequest, response -> {
if (response.getEntity() != null) {
String body = EntityUtils.toString(response.getEntity());
if (tp.getType() == String.class) {
return new Client5Resp<>(response.getCode(), body, (T)body);
}
// 当需要区分更多类型时可以增加定义
else {
T t = JacksonUtil.extractByType(body, tp);
return new Client5Resp<>(response.getCode(), body, t);
}
} else {
return new Client5Resp<>(response.getCode(), null, null);
}
});
log.info("rsp:{}, body:{}", resp.getCode(), resp.getRaw());
return resp;
} catch (IOException|NoSuchAlgorithmException|KeyStoreException|KeyManagementException e) {
// 当异常也需要返回 Client5Resp 类型对象时可以在catch中封装
log.error(e.getMessage(), e);
}
return null;
}
首先是超时设置
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(60, TimeUnit.SECONDS)
.setResponseTimeout(60, TimeUnit.SECONDS)
.build();
然后是 Header
List<Header> headers = List.of(
new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
new BasicHeader(HttpHeaders.ACCEPT, "application/json"));
在 HttpGet/HttpPost 中设置
HttpGet httpGet = new HttpGet(...);
if (headers != null) {
for (Header header : headers) {
httpGet.addHeader(header);
}
}
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
httpGet.setConfig(requestConfig);
在 HttpClient5 中, 增加 SSL TrustAllStrategy 的方法也有变化, 这是获取 CloseableHttpClient 的代码
final RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(60, TimeUnit.SECONDS)
.setResponseTimeout(60, TimeUnit.SECONDS)
.build();
final BasicCookieStore defaultCookieStore = new BasicCookieStore();
final SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustAllStrategy()).build();
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
.setSslContext(sslcontext).build();
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslSocketFactory).build();
return HttpClients.custom()
.setDefaultCookieStore(defaultCookieStore)
.setDefaultRequestConfig(defaultRequestConfig)
.setConnectionManager(cm)
.evictExpiredConnections()
.build();
在 HttpClient5 中, RequestConfig.Builder.setProxy()方法已经 Deprecated
@Deprecated
public RequestConfig.Builder setProxy(HttpHost proxy) {
this.proxy = proxy;
return this;
}
需要使用 HttpClientBuilder.setRoutePlanner(HttpRoutePlanner routePlanner) 进行设置, 和SSL一起, 获取client的代码变成
final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
return HttpClients.custom()
.setDefaultCookieStore(defaultCookieStore)
.setDefaultRequestConfig(defaultRequestConfig)
.setRoutePlanner(routePlanner)
.setConnectionManager(cm)
.evictExpiredConnections()
.build();
如果需要用户名密码, 需要再增加一个 CredentialsProvider, 变成
final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(authUser, authPasswd.toCharArray()));
return HttpClients.custom()
.setDefaultCookieStore(defaultCookieStore)
.setDefaultRequestConfig(defaultRequestConfig)
.setDefaultCredentialsProvider(credsProvider)
.setRoutePlanner(routePlanner)
.setConnectionManager(cm)
.evictExpiredConnections()
.build();
如果需要随时切换 proxy, 需要自己实现一个 HttpRoutePlanner
public static class DynamicProxyRoutePlanner implements HttpRoutePlanner {
private DefaultProxyRoutePlanner planner;
public DynamicProxyRoutePlanner(HttpHost host){
planner = new DefaultProxyRoutePlanner(host);
}
public void setProxy(HttpHost host){
planner = new DefaultProxyRoutePlanner(host);
}
public HttpRoute determineRoute(HttpHost target, HttpContext context) throws HttpException {
return planner.determineRoute(target, context);
}
}
然后在代码中进行切换
HttpHost proxy = new HttpHost("127.0.0.1", 1080);
DynamicProxyRoutePlanner routePlanner = new DynamicProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
// 换代理
routePlanner.setProxy(new HttpHost("192.168.0.1", 1081));
首先是构造 HttpEntity 的方法, 这个方法中设置请求为 1个文件 + 多个随表单参数
public static HttpEntity httpEntityBuild(NameValuePair fileNvp, List<NameValuePair> nvps) {
File file = new File(fileNvp.getValue());
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);
if (nvps != null && nvps.size() > 0) {
for (NameValuePair nvp : nvps) {
builder.addTextBody(nvp.getName(), nvp.getValue(), ContentType.DEFAULT_BINARY);
}
}
builder.addBinaryBody(fileNvp.getName(), file, ContentType.DEFAULT_BINARY, fileNvp.getValue());
return builder.build();
}
请求流程
// 构造一个文件参数, 其它参数留空
NameValuePair fileNvp = new BasicNameValuePair("sendfile", filePath);
HttpEntity entity = httpEntityBuild(fileNvp, null);
HttpPost httpPost = new HttpPost(api);
httpPost.setEntity(entity);
try (CloseableHttpClient client = getClient(...)) {
Client5Resp<T> resp = client.execute(httpPost, response->{
...
});
注意: 在使用 HttpMultipartMode 时对 HttpEntity 设置 Header 要谨慎, 因为 HttpClient 会对 Content-Type增加 Boundary 后缀, 而这个是服务端判断文件边界的重要参数. 如果设置自定义 Header, 需要检查 boundary 是否正确生成. 如果没有的话需要自定义 Content-Type 将 boundary 加进去, 并且通过 EntityBuilder.setBoundary() 将自定义的 boundary 值传给 HttpEntity.
目录前言滤波电路科普主要分类实际情况单位的概念常用评价参数函数型滤波器简单分析滤波电路构成低通滤波器RC低通滤波器RL低通滤波器高通滤波器RC高通滤波器RL高通滤波器部分摘自《LC滤波器设计与制作》,侵权删。前言最近需要学习放大电路和滤波电路,但是由于只在之前做音乐频谱分析仪的时候简单了解过一点点运放,所以也是相当从零开始学习了。滤波电路科普主要分类滤波器:主要是从不同频率的成分中提取出特定频率的信号。有源滤波器:由RC元件与运算放大器组成的滤波器。可滤除某一次或多次谐波,最普通易于采用的无源滤波器结构是将电感与电容串联,可对主要次谐波(3、5、7)构成低阻抗旁路。无源滤波器:无源滤波器,又称
我正在尝试在ruby脚本中连接到服务器https://www.xpiron.com/schedule。但是,当我尝试连接时:require'open-uri'doc=open('https://www.xpiron.com/schedule')我收到以下错误消息:OpenSSL::SSL::SSLError:SSL_connectreturned=1errno=0state=SSLv2/v3readserverhelloA:sslv3alertunexpectedmessagefrom/usr/local/lib/ruby/1.9.1/net/http.rb:678:in`conn
我正在使用Rails3.2.6和Stipe进行支付。是否有可能在不购买ssl证书的情况下进行付款。我可以使用Stripe页面作为我的支付页面吗? 最佳答案 您可以使用stripe.js在技术上跳过SSL但我强烈建议您设置SSL。它所做的是将信用卡信息直接传递给stripe,然后stripe会给你一个token,用于实际进行收费。这样做意味着信用卡信息永远不会接触您的服务器,您不必担心PCI合规性。但是,您仍应设置SSL以防止中间人攻击。您可以在https://stripe.com/docs/tutorials/forms找到有关如何
尝试通过SSL连接到ImgurAPI时出现错误。这是代码和错误:API_URI=URI.parse('https://api.imgur.com')API_PUBLIC_KEY='Client-ID--'ENDPOINTS={:image=>'/3/image',:gallery=>'/3/gallery'}#Public:Uploadanimage##args-Theimagepathfortheimagetoupload#defupload(image_path)http=Net::HTTP.new(API_URI.host)http.use_ssl=truehttp.verify
写在之前Shader变体、Shader属性定义技巧、自定义材质面板,这三个知识点任何一个单拿出来都是一套知识体系,不能一概而论,本文章目的在于将学习和实际工作中遇见的问题进行总结,类似于网络笔记之用,方便后续回顾查看,如有以偏概全、不祥不尽之处,还望海涵。1、Shader变体先看一段代码......Properties{ [KeywordEnum(on,off)]USL_USE_COL("IsUseColorMixTex?",int)=0 [Toggle(IS_RED_ON)]_IsRed("IsRed?",int)=0}......//中间省略,后续会有完整代码 #pragmamulti_c
TCL脚本语言简介•TCL(ToolCommandLanguage)是一种解释执行的脚本语言(ScriptingLanguage),它提供了通用的编程能力:支持变量、过程和控制结构;同时TCL还拥有一个功能强大的固有的核心命令集。TCL经常被用于快速原型开发,脚本编程,GUI和测试等方面。•实际上包含了两个部分:一个语言和一个库。首先,Tcl是一种简单的脚本语言,主要使用于发布命令给一些互交程序如文本编辑器、调试器和shell。由于TCL的解释器是用C\C++语言的过程库实现的,因此在某种意义上我们又可以把TCL看作C库,这个库中有丰富的用于扩展TCL命令的C\C++过程和函数,所以,Tcl是
我编写了一个使用ruby线程的代码。require'rubygems'require'net/http'require'uri'defget_response()uri=URI.parse('https://..........')http=Net::HTTP.new(uri.host,uri.port)http.use_ssl=true----------endt1=[]15.timesdo|i|t1[i]=Thread.new{hit_mdm(i)sleep(rand(0)/10.0)}endt1.each{|t|t.join}代码工作正常,但是当程序执行到最后时它会抛出以下错
我正在运行本地puma服务器,但无法在SSL下加载资源。我有一个本地签名的证书。我正在尝试使用以下配置运行服务器:puma-b'ssl://127.0.0.1:9292?key=/path/to/certs/localhost.unecrypted.key&cert=/path/to/certs/localhost.crt'现在,当我访问https://localhost:9292或https://127.0.0.1:9292时,浏览器只是旋转并且没有来自服务器的响应。不返回任何资源。它两次向我显示HTML标题标签,但几乎总是什么也得不到。有什么想法吗?其他想法?确实需要在本地运行此应
在安装了openssllib的linux机器上,当您执行带有“-nodes”选项的“opensslpkcs12”时,您将获得带有未加密私钥的输出,但如果您跳过–nodes选项,则输出将具有加密的私钥。e.g.opensslpkcs12-intest.pfx-outtest.pem你应该看到像下面这样加密的私钥-----BEGINENCRYPTEDPRIVATEKEY-----MIIFDjBABgkqhkiGG7s=-----ENDENCRYPTEDPRIVATEKEY-----如何使用ruby的开放ssl库实现上述目标?这就是我用ruby生成私钥的方式:@private_key
我正在尝试使用RubyEventMachine访问使用SSL证书身份验证的HTTPSWeb服务,但我没有让它工作。我编写了以下简单代码块来对其进行端到端测试:require'rubygems'require'em-http'EventMachine.rundourl='https://foobar.com/'ssl_opts={:private_key_file=>'/tmp/private.key',:cert_chain_file=>'/tmp/ca.pem',:verify_peer=>false}http=EventMachine::HttpRequest.new(url).g