使用HttpClient设置自定义的DNS

要想使 DefaultHttpClient 对象使用自定义的 DNS 解析(比如将 blogjava.net 关联到 127.0.0.1,使其访问 "http://blogjava.net" 时请求本地服务器),可以用下面的办法(我在官网上没找到相关文章,是看了源代码自己琢磨出来的,也不是道是不是标准做法)

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * 在 httpclient 4.2 中使用自定义的 DNS 解析
 
*/
public  class CustomDnsResolverDemo {

     public  static  void main(String[] args)  throws Exception {

         //  创建自定义的 ConnectionManager
        BasicClientConnectionManager connectionManager =  new BasicClientConnectionManager() {

            @Override
             protected ClientConnectionOperator createConnectionOperator(SchemeRegistry schreg) {
                 return  new DefaultClientConnectionOperator(schreg,  new MyDnsResolver());
            }
        };

         //  创建 HttpClient 对象
        DefaultHttpClient httpclient =  new DefaultHttpClient(connectionManager);

         //  构造请求
        HttpGet httpget =  new HttpGet("https://www.google.com/");
        System.out.println(httpget.getRequestLine());

         //  发送请求并返回结果
        HttpResponse response = httpclient.execute(httpget);
        System.out.println(response.getEntity().getContentType());
        System.out.println(response.getStatusLine());

         //  这句不是必须的,只是让程序结束更快点
        httpclient.getConnectionManager().shutdown();
    }

     //  自定义的 DNS 解析类
     private  static  class MyDnsResolver  implements DnsResolver {

         private  static  final Map MAPPINGS =  new HashMap();

         static {
            addResolve("www.google.com", "74.125.134.138");
        }

         private  static  void addResolve(String host, String ip) {
             try {
                MAPPINGS.put(host,  new InetAddress[]{InetAddress.getByName(ip)});
            }  catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

        @Override
         public InetAddress[] resolve(String host)  throws UnknownHostException {
             return MAPPINGS.containsKey(host) ? MAPPINGS.get(host) :  new InetAddress[0];
        }
    }
}

你可能感兴趣的:(javaEE)