从 第三方 获取 ip 与 端口
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientTools {
public static String proxyByIp(String url, Map<String, String> headers,String ip,int port) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpHost proxy = new HttpHost(ip, port);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(TIME_OUT)
.setConnectTimeout(TIME_OUT)
.setProxy(proxy)
.build();
HttpGet httpGet = new HttpGet(url);
if (headers != null) {
for (String key : headers.keySet()) {
httpGet.addHeader(key, headers.get(key));
}
}
httpGet.setConfig(requestConfig);
try {
CloseableHttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
// 如果状态码不是200,返回空,表示失败
int htttpStatusCode = response.getStatusLine().getStatusCode();
if (200 == htttpStatusCode ) {
return EntityUtils.toString(response.getEntity(),"utf8");
}
} catch (Exception e) {
LOG.error("url={}", url);
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}