需求
应用服务器不能直接通外网,需配置代理服务器。
直接代理在发起端就不需要额外操作,直接就是往代理服务器指定端口发送请求即可, 直接转发到被代理地址。
直接代理nginx配置:
server {
resolver 119.6.6.6;
listen 8080;
location / {
# proxy_pass https://此处为被代理地址$request_uri;
proxy_pass https://xxxx.xxxx.xxxx$request_uri;
proxy_buffer_size 64k;
proxy_buffers 32 32k;
proxy_busy_buffers_size 128k;
}
}
间接代理需要在请求发起的地方指定通过代理方式访问,这里举CloseableHttpClient的发起请求的例子。
间接代理JAVA代码:
private String doPost(String token, Map<String, String> postParams) {
CloseableHttpClient httpclient = null;
HttpPost post = null;
CloseableHttpResponse response1 = null;
Gson gson = new Gson();
int statusCode = 0;// 返回的结果
String result = "";
try {
if (isproxy) {
Trace.log(Trace.COMPONENT_ACTION, "通过代理方式访问" + proxyIP + ":" + proxyport);
// 把代理设置到请求配置 代理IP 端口
HttpHost proxy = new HttpHost(proxyIP, Integer.parseInt(proxyport));
// 超时时间单位为毫秒
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).setProxy(proxy).build();
httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
} else {
httpclient = HttpClients.custom().build();
}
post = new HttpPost(baseurl);
post.setHeader("Content-Type", "application/json;charset=UTF-8");
post.setHeader("Accept", "application/json");
post.setHeader("token", token);
post.setEntity(new StringEntity(gson.toJson(postParams), "UTF-8"));
response1 = httpclient.execute(post);
statusCode = response1.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
result = EntityUtils.toString(response1.getEntity());// 返回json格式
} else {
throw new TranFailException("JD_0037", "服务器接口网络异常" + statusCode);
}
// 判断get请求响应结果
response1.close();
post.releaseConnection();
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (response1 != null) {
response1.close();
}
if (post != null) {
post.releaseConnection();
}
} catch (IOException e) {
} finally {
try {
if (httpclient != null) {
httpclient.close();
}
} catch (IOException e) {
}
}
}
return result;
}
间接代理nginx配置:
server {
listen 8086;
resolver 119.6.6.6;
proxy_connect;
#proxy_connect_allow 443 563;
location / {
access_log logs/ngxin_8086.log main;
proxy_pass https://$host$request_uri;
proxy_buffer_size 64k;
proxy_buffers 32 32k;
proxy_busy_buffers_size 128k;
proxy_set_header Content-Type $http_content_type;
proxy_set_header Host $http_host;
proxy_set_header Authorization $http_Authorization;
}
1 thought on “Nginx请求直接代理与间接代理配置”