栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

前言

调用接口报错

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.*;
 


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;


    
    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", "*
    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;
    }
    
    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;
    }


    
    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).build();
        httpGet.setConfig(requestConfig);
        return httpClient;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955023.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号