How can I specify the local address on a java.net.URLConnection?

后端 未结 4 1236
名媛妹妹
名媛妹妹 2020-12-01 06:50

My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a URLConnection.

How can I

4条回答
  •  萌比男神i
    2020-12-01 07:30

    Using the Apache commons HttpClient I have also found the following to work (removed try/catch for clarity):

    HostConfiguration hostConfiguration = new HostConfiguration();
    byte b[] = new byte[4];
    b[0] = new Integer(192).byteValue();
    b[1] = new Integer(168).byteValue();
    b[2] = new Integer(1).byteValue();
    b[3] = new Integer(11).byteValue();
    
    hostConfiguration.setLocalAddress(InetAddress.getByAddress(b));
    
    HttpClient client = new HttpClient();
    client.setHostConfiguration(hostConfiguration);
    GetMethod method = new GetMethod("http://remoteserver/");
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
        new DefaultHttpMethodRetryHandler(3, false));
    int statusCode = client.executeMethod(method);
    
    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
    }
    
    byte[] responseBody = method.getResponseBody();
    System.out.println(new String(responseBody));");
    

    However, I still wonder what would happen if the gateway of the IP is down (192.168.1.11 in this case). Will the next gateway be tried or will it fail?

提交回复
热议问题