Created
December 25, 2016 23:35
-
-
Save sabburo/64732f30a16448a20c7c11c18d8a4265 to your computer and use it in GitHub Desktop.
HttpClient4.5を使用してProxy配下からアクセスする
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
package howtohttpclient; | |
import java.util.ArrayList; | |
import java.util.List; | |
import org.apache.http.Header; | |
import org.apache.http.HttpHost; | |
import org.apache.http.auth.AuthScope; | |
import org.apache.http.auth.UsernamePasswordCredentials; | |
import org.apache.http.client.CredentialsProvider; | |
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.BasicCredentialsProvider; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
import org.apache.http.message.BasicHeader; | |
import org.apache.http.util.EntityUtils; | |
public class GetSiteInfo { | |
public static void main(String[] args) throws Exception { | |
//アクセス対象のURL | |
String uri ="www.google.co.jp"; | |
String userAgent =""; | |
//Proxyサーバと認証情報のセット | |
CredentialsProvider credsProvider = new BasicCredentialsProvider(); | |
credsProvider.setCredentials( | |
new AuthScope("proxy_host", proxyport), | |
new UsernamePasswordCredentials("proxy_id", "proxy_password")); | |
//ヘッダー情報のセット | |
List<Header> headers = new ArrayList<Header>(); | |
headers.add(new BasicHeader("Accept-Charset","utf-8")); | |
headers.add(new BasicHeader("Accept-Language","ja, en;q=0.8")); | |
headers.add(new BasicHeader("User-Agent",userAgent)); | |
CloseableHttpClient httpclient = HttpClients.custom() | |
.setDefaultCredentialsProvider(credsProvider) | |
.setDefaultHeaders(headers).build(); | |
try { | |
HttpHost target = new HttpHost(uri, 80, "http"); | |
HttpHost proxy = new HttpHost("proxy_host", porxy_port); | |
RequestConfig config = RequestConfig.custom() | |
.setProxy(proxy) | |
.build(); | |
HttpGet httpget = new HttpGet(""); | |
httpget.setConfig(config); | |
System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy); | |
CloseableHttpResponse response = httpclient.execute(target, httpget); | |
try { | |
System.out.println("----------------------------------------"); | |
System.out.println(response.getStatusLine()); | |
System.out.println(EntityUtils.toString(response.getEntity())); | |
} finally { | |
response.close(); | |
} | |
} finally { | |
httpclient.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment