今天通过nginx代理下载pdf报这个错,网上查了很多资料,说的大部分都是Android studio这个的解决办法,几乎没有针对nginx的处理,部分说是需要配hosts,配了hosts也没用,有一些说是要增加proxy_set_header Host $http_host;这个配置,也不能解决我的问题,这边记录一下针对我这边出现问题处理方式。
代码相对简单
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为5秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
计划是这么直接访问,但是想到没办法出网,直接就报域名访问不到,想到需要走代理,首先在nginx配置相关代理信息
server {
listen 8088;
#listen somename:8080;
server_name file.test.ess.tencent.cn;
location /file {
proxy_pass https://xxx.xx.xx/file;
proxy_cache_valid 200 1y;
add_header Nginx-Cache "$upstream_cache_status";
proxy_ssl_session_reuse off;
proxy_ssl_server_name on;
proxy_ssl_name xxx.xx.xx;
proxy_ssl_protocols TLSv1.2;
proxy_set_header X-Real-IP $remote_addr;
#proxy_set_header Host $http_host;
}
}
配置完成后,想着是不是代码要走代理修改代码如下
URL url = new URL(urlStr);
Proxy proxy=new Proxy(Proxy.Type.HTTP, new InetSocketAddress(IP, PORT));
HttpURLConnection conn = (HttpURLConnection)url.openConnection(proxy);
//设置超时间为5秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
确认代理后就发现报题目中的错误,后来发现自己想复杂了,nginx已经帮忙代理了,不需要这边再次代理,直接把地址地换成自己的ip+端口即可,让nginx去处理出网的问题
最终确认代码和nginx配置如下:文章来源:https://www.toymoban.com/news/detail-522646.html
urlStr = urlStr.replace("https://xxx.xx.xx","http://IP:PORT");
URL url = new URL(urlStr);
// Proxy proxy=new Proxy(Proxy.Type.HTTP, new InetSocketAddress(IP, PORT));
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为5秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
server {
listen 8088;
#listen somename:8080;
server_name xxx.xx.xx;
location / {
proxy_pass https://xxx.xx.xx;
proxy_cache_valid 200 1y;
add_header Nginx-Cache "$upstream_cache_status";
proxy_ssl_session_reuse off;
proxy_ssl_server_name on;
proxy_ssl_name xxx.xx.xx;
proxy_ssl_protocols TLSv1.2;
proxy_set_header X-Real-IP $remote_addr;
#proxy_set_header Host $http_host;
}
}
记录本次问题,转载注明出处文章来源地址https://www.toymoban.com/news/detail-522646.html
到了这里,关于Unable to tunnel through proxy. Proxy returns “HTTP/1.1 400 Bad request的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!