Skip to content

Instantly share code, notes, and snippets.

@ChinaXing
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChinaXing/93fec08b1c0b33ee733e to your computer and use it in GitHub Desktop.
Save ChinaXing/93fec08b1c0b33ee733e to your computer and use it in GitHub Desktop.
创建http请求的时候指定客户端IP
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
import java.net.*;
/**
* create http Connection and specify local ip address
* Use HttpClient 4.x
* <p/>
* Created by LambdaCat on 15/4/26.
*/
public class SpecifyHttpConnectionLocalAddress {
@Test
public void t2() {
try {
CloseableHttpClient httpClient = HttpClientBuilder
.create()
.setDefaultRequestConfig(RequestConfig.custom()
.setLocalAddress(
InetAddress.getByAddress(new byte[]{(byte) 192, (byte) 168, 10, (byte) 157})
).build()
).build();
CloseableHttpResponse response = httpClient.execute(new HttpGet("http://www.treebear.cn"));
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment