java/HttpClient:get、post 设置代理(java.net.UnknownHostException)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


前言

调用接口报错

java.net.UnknownHostException: qyapi.weixin.qq.com

at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1324)
at java.net.InetAddress.getAllByName0(InetAddress.java:1277)
at java.net.InetAddress.getAllByName(InetAddress.java:1193)
at java.net.InetAddress.getAllByName(InetAddress.java:1127)

原因

内网需要代理出外网,HttpClient无法连接外网,写一个工具类

解决

​​参考文章​​

import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;


/**
* @Author ZhangLe
* @Date 2020/10/30 15:58
*/
public class ProxySendUtils {

//消息体内容类型
public static final String CONTENT_TYPE = "Content-Type";
// 以秒为单位
static int timeout = 10 * 1000;
//代理IP
static String host = "127.0.0.1";
//代理端口
static int port = 8088;


/**
* 向指定URL发送GET方法的请求
* @param url
* @return
*/
public String sendGet1(String url) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);

// 创建代理服务器
InetSocketAddress addr = new InetSocketAddress(host, port);
//http 代理
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection(proxy);

// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;");
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);

// 建立实际的连接
connection.connect();

// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gbk"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}

/**
* 发送代理get
* @param url
* @param charset 默认填 UTF-8
* @return
* @throws HttpException
* @throws IOException
*/
public String sendGet2(String url, String charset) throws HttpException, IOException {
String json = null;
HttpGet httpGet = new HttpGet();
CloseableHttpClient client = setProxy(httpGet, host, port);
// 设置参数
try {
httpGet.setURI(new URI(url));
} catch (URISyntaxException e) {
throw new HttpException("请求url格式错误。"+e.getMessage());
}
// 发送请求
HttpResponse httpResponse = client.execute(httpGet);
// 获取返回的数据
HttpEntity entity = httpResponse.getEntity();
byte[] body = EntityUtils.toByteArray(entity);
StatusLine sL = httpResponse.getStatusLine();
int statusCode = sL.getStatusCode();
if (statusCode == 200) {
json = new String(body, charset);
entity.consumeContent();
} else {
throw new HttpException("statusCode="+statusCode);
}
return json;
}
/**
* 创建发送请求post实体
*
* @param charset 消息编码 默认填 UTF-8
* @param contentType 消息体内容类型,默认可以写工具类 CONTENT_TYPE
* @param url 消息发送请求地址
* @param data 为post数据
* @return
* @throws
*/
public String sendPost(String charset, String contentType, String url, String data) throws Exception {

HttpPost httpPost = new HttpPost(url );

CloseableHttpClient client = setProxy(httpPost, host, port);
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36");

httpPost.setHeader(CONTENT_TYPE, contentType);
httpPost.setEntity(new StringEntity(data, charset));
CloseableHttpResponse response = client.execute(httpPost);

String resp = null;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, charset);
EntityUtils.consume(entity);
} finally {
response.close();
}
LoggerFactory.getLogger(getClass()).info( "call [{}], param:{}, resp:{}", url, data, resp);
return resp;
}


/**
* 设置代理
*
* @param httpGet
* @param proxyIp
* @param proxyPort
* @return
*/
public static CloseableHttpClient setProxy(HttpRequestBase httpGet, String proxyIp, int proxyPort) {
// 创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置代理IP、端口
HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
//也可以设置超时时间 需要了放开注释 不需要忽略
/* RequestConfig requestConfig = RequestConfig
.custom()
.setProxy(proxy)
.setConnectTimeout(timeout)
.setSocketTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.build();*/
RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
httpGet.setConfig(requestConfig);
return httpClient;
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java