| 知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
首先確認你的伺服器是支持 HTTP2,HTTP2配置方法可以參考 《Netkiller Web 手札》
下面是我的例子僅供參考,Nginx 開啟 http2 代理後面的 Spring Cloud 介面。
server {
listen 80;
listen 443 ssl http2;
server_name api.netkiller.cn;
ssl_certificate ssl/netkiller.cn.crt;
ssl_certificate_key ssl/netkiller.cn.key;
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 60m;
charset utf-8;
access_log /var/log/nginx/api.netkiller.cn.access.log;
error_page 497 https://$host$uri?$args;
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
安卓程序如下
String url = "https://api.netkiller.cn/member/json";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("okhttp", "Connect timeout. " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String text = response.body().string();
Log.d("okhttp", "HTTP Code " + response.code() + " TEXT " + text);
Log.d("okhttp", "Protocol: " + response.protocol());
}
});
運行結果
D/okhttp: HTTP Code 200 TEXT {"status":false,"reason":"","code":0,"data":{"id":null,"username":"12322228888","mobile":"12322228888","password":"123456","wechat":"微信ID","role":"Organization","captcha":null,"createDate":"2018-10-25 09:25:23","updateDate":null}}
Protocol: h2
輸出 h2 表示當前介面與伺服器連接是通過 http2 完成。