Last active
August 29, 2015 14:24
-
-
Save ChinaXing/93fec08b1c0b33ee733e to your computer and use it in GitHub Desktop.
创建http请求的时候指定客户端IP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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