HttpClient 4コードサンプル
14438 ワード
HttpClient 4.XコードサンプルメモここでhttpClient 4.0とhttpClient 4.3+のコード構造は異なることは少ない.
1. httpClient 4.0
2. httpClient 4.3+
3.httpClient 4.3+でのクッキー操作
4.httpClientとmultipart-form提出
5. pom.xml
1. httpClient 4.0
public class HttpClientUtil {
private final static Log log = LogFactory.getLog(HttpClientUtil.class);
private static HttpClient httpClient = new DefaultHttpClient();;
public static final String CHARSET = "UTF-8";
static {
httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
}
public static String httpGet(String url, Map<String, String> params){
return httpGet(url, params,"utf-8");
}
public static String httpPost(String url, Map<String, String> params){
return httpPost(url, params,"utf-8");
}
/**
* @param url http://taobao.com/test.action
* @param params ,
* @return
*/
public static String httpGet(String url, Map<String, String> params,String charset) {
if(StringUtils.isBlank(url)){
return null;
}
try {
if(params != null && !params.isEmpty()){
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for(Entry<String,String> entry : params.entrySet()){
String value = entry.getValue();
if(value != null){
pairs.add(new BasicNameValuePair(entry.getKey(),value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpClient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpget.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
log.error("http !url:" + url, e);
} finally {
httpClient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
}
return null;
}
/**
* @param url http://360buy.com/test.action
* @param params ,
* @return
*/
public static String httpPost(String url, Map<String, String> params,String charset) {
if(StringUtils.isBlank(url)){
return null;
}
try{
HttpPost httpPost = new HttpPost(url);
if(params != null && !params.isEmpty()){
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for(Entry<String,String> entry : params.entrySet()){
String value = entry.getValue();
if(value != null){
pairs.add(new BasicNameValuePair(entry.getKey(),value));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(pairs,charset));
}
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
log.error("http !url:" + url, e);
} finally {
httpClient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
}
return null;
}
/**
* body form
* @param url
* @return
* @throws Exception
*/
public static String httpPost(String url,Map<String,String> params,HttpEntity requestEntity) throws Exception{
if(params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
String queryString = EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
if(url.indexOf("?") > 0) {
url += "&" + queryString;
} else {
url += "?" + queryString;
}
}
HttpPost httpPost = new HttpPost(url);
if(requestEntity != null) {
httpPost.setEntity(requestEntity);
}
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
return result;
} finally {
response.close();
}
}
2. httpClient 4.3+
public class HttpClientUtil {
private static final CloseableHttpClient httpClient;
public static final String CHARSET = "UTF-8";
static {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(60000)
.setSocketTimeout(15000)
.build();
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.build();
}
public static String httpGet(String url, Map<String, String> params){
return httpGet(url, params,"utf-8");
}
/**
* @param url http://taobao.com/test.action
* @param params ,
* @return
*/
public static String httpGet(String url, Map<String, String> params,String charset) {
if(StringUtils.isBlank(url)){
return null;
}
try {
if(params != null && !params.isEmpty()){
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for(Map.Entry<String,String> entry : params.entrySet()){
String value = entry.getValue();
if(value != null){
pairs.add(new BasicNameValuePair(entry.getKey(),value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpget.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3.httpClient 4.3+でのクッキー操作
public class HttpUtils {
private static final CloseableHttpClient httpClient;
public static final String CHARSET = "UTF-8";
static {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(6000)
.setSocketTimeout(6000)
.build();
Registry<CookieSpecProvider> registry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH,
new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory())
.build();
httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.setDefaultCookieSpecRegistry(registry)
.setDefaultCookieStore(new BasicCookieStore()) //
.build();
}
public static void main(String[] args) throws Exception{
login();//server cookie
getOrder();// cookie
}
public static void getOrder() throws Exception{
String url = "http://test.domain/user/order.jhtml";
HttpGet httpGet = new HttpGet(url);
HttpClientContext clientContext = HttpClientContext.create();
// ,httpClient , cookie,
// client cookie ,
/**
CookieStore cookieStore = new BasicCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
for(Cookie cookie : cookies) {
cookieStore.addCookie(cookie);
}
clientContext.setCookieStore(cookieStore);
**/
CloseableHttpResponse response = httpClient.execute(httpGet,clientContext);
try {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
System.out.println(result);
} finally {
response.close();
}
}
public static void login() throws Exception{
String url = "http://test.domain/user/login.jhtml";
Map<String,String> params = new HashMap<String,String>();
params.put("phone","18600000000");
params.put("password","123123");
if(params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
}
HttpPost httpPost = new HttpPost(url);
HttpClientContext clientContext = HttpClientContext.create();
CloseableHttpResponse response = httpClient.execute(httpPost,clientContext);
try {
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
System.out.println(result);//
// " " cookie
// cookie HttpClient cookieStore ,
CookieStore cookieStore = clientContext.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
for(Cookie cookie : cookies) {
System.out.println(cookie.getName() + "," + cookie.getValue());
}
} finally {
response.close();
}
}
}
4.httpClientとmultipart-form提出
String url = "http://test.domain/update_user.jhtml";
HttpPost post = new HttpPost(url);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
FileBody fileBody = new FileBody(new File("D:\\test.jpg"));
entityBuilder.addPart("icon",fileBody);//
ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
StringBody stringBody = new StringBody(" ",contentType);
entityBuilder.addPart("name",stringBody);
post.setEntity(entityBuilder.build());
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
String result = null;
System.out.println(response.getStatusLine());
if (entity != null) {
long length = entity.getContentLength();
System.out.println(length);
if (length != -1) {
result = EntityUtils.toString(entity, "utf-8");
}
} else {
System.out.println("11:null");
}
EntityUtils.consume(entity);
response.close();
5. pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3</version>
</dependency>