package com.lazycat.httpclienttool.httpclient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.lazycat.httpclienttool.entry.HttpFile;
public class DefaultHttpTemplate extends RestTemplate implements HttpTemplate{
private RestClient restClient;
private static final Charset DEFAULT_CHARSET = Charset.forName("utf-8");
public DefaultHttpTemplate() {
restClient = new DefaultRestClient();
if(restClient.getFactory() != null)
setRequestFactory(restClient.getFactory());
initMessageConverters();
}
private void initMessageConverters(){
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
this.setMessageConverters(messageConverters);
}
public <T> T getForObject(String url,Map<String,Object> paramUrl,Map<String,Object> paramQuery,Class<T> responseType){
Assert.hasLength(url,"request url must be not null or empty");
Assert.notNull(responseType,"response type must be not null");
url = prepareUrl(url,paramQuery);
if(paramUrl == null)
paramUrl = Collections.emptyMap();
return getForObject(url, responseType,paramUrl);
}
public <T> T postForObject(String url,Map<String,Object> paramUrl,Map<String,Object> paramQuery,Map<String,Object> paramBody,Map<String,Object> paramHead,Class<T> responseType){
Assert.hasLength(url,"request url must be not null or empty");
Assert.notNull(responseType,"response type shold not be null");
url = prepareUrl(url,paramQuery);
paramBody = changeValueToString(paramBody);
paramUrl = changeValueToString(paramUrl);
paramHead = changeValueToString(paramHead);
if(paramUrl == null){
paramUrl = Collections.emptyMap();
}
if(isMultipart(paramBody)){
return postForObjectMutipart(url,paramUrl,paramBody,paramHead,responseType);
}else{
MultiValueMap<String, Object> multiValues = new LinkedMultiValueMap<String, Object>();
multiValues.setAll(paramBody);
if(paramHead == null || paramHead.isEmpty()){
return this.postForObject(url, multiValues, responseType, paramUrl);
}else{
HttpHeaders headers = new HttpHeaders();
headers.setAll(translateMap(changeValueToString(paramHead)));
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String,Object>>(multiValues,headers);
return postForObject(url,entity,responseType,paramUrl);
}
}
}
private String prepareUrl(String url, Map<String, Object> paramQuery) {
if(paramQuery == null || paramQuery.isEmpty())
return url;
paramQuery = changeValueToString(paramQuery);
int index = url.indexOf('?');
boolean isFirst = false;
if(index < 0 && paramQuery.size() > 0){
url += '?';
isFirst = true;
}
for(Map.Entry<String, Object> entry : paramQuery.entrySet()){
if(isFirst){
if(entry.getValue() == null || "".equals(entry.getValue())){
url += entry.getKey();
}else{
url += entry.getKey()+'='+entry.getValue();
}
isFirst = false;
}else{
if(entry.getValue() == null || "".equals(entry.getValue())){
url += '&'+entry.getKey();
}else{
url += '&'+entry.getKey()+'='+entry.getValue();
}
}
}
return url;
}
@SuppressWarnings("unchecked")
private <T> T postForObjectMutipart(String url,Map<String,Object> paramUrl,Map<String,Object> paramBody,Map<String,Object> paramHead,Class<T> responseType){
HttpPost post = new HttpPost();
MultipartEntity entity = null;
if(paramUrl != null && !paramUrl.isEmpty()){
for(Map.Entry<String, Object> paramurl : paramUrl.entrySet()){
url.replaceAll(paramurl.getKey(), String.valueOf(paramurl.getValue()));
}
}
try{
post.setURI(new URI(url));
}catch(Exception e){
e.printStackTrace();
return null;
}
if(paramBody != null && !paramBody.isEmpty()){
entity = new MultipartEntity();
for(Map.Entry<String, Object> body : paramBody.entrySet()){
if(HttpFile.class.isAssignableFrom(body.getValue().getClass())){
HttpFile httpFile = (HttpFile) body.getValue();
if(httpFile.getMimeType() == null || httpFile.getMimeType().equals("")){
entity.addPart(body.getKey(),new ByteArrayBody(httpFile.getFile(),httpFile.getFilename()));
}else{
entity.addPart(body.getKey(),new ByteArrayBody(httpFile.getFile(),httpFile.getMimeType(),httpFile.getFilename()));
}
}else if(String.class.isAssignableFrom(body.getValue().getClass())){
try {
entity.addPart(body.getKey(),new StringBody((String)body.getValue(),DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
}
post.setEntity(entity);
}
if(paramHead != null && !paramHead.isEmpty()){
for(Map.Entry<String, Object> head : paramHead.entrySet()){
post.setHeader(head.getKey(), String.valueOf(head.getValue()));
}
}
try {
HttpResponse response = restClient.getHttpClient().execute(post);
if(responseType == String.class){
return (T) EntityUtils.toString(response.getEntity());
}else if(responseType == byte[].class)
{
return (T) EntityUtils.toByteArray(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private boolean isMultipart(Map<String, Object> map) {
for(Map.Entry<String, Object> e : map.entrySet()){
if(HttpFile.class.isAssignableFrom(e.getValue().getClass())){
return true;
}
}
return false;
}
private Map<String,Object> changeValueToString(Map<String,Object> request){
if(request == null || request.isEmpty())
return request;
Map<String,Object> retValues = new HashMap<String, Object>();
for(Map.Entry<String, Object> entity : request.entrySet()){
Object value = entity.getValue();
Class<?> valueClass = value.getClass();
if(valueClass == String.class
||valueClass == Integer.class
||valueClass == Long.class
||valueClass == Short.class
||valueClass == Float.class
||valueClass == Double.class
||valueClass == Byte.class
||valueClass == Character.class
||valueClass == Boolean.class){
retValues.put(entity.getKey(),String.valueOf(value));
}else{
retValues.put(entity.getKey(), entity.getValue());
}
}
return retValues;
}
private Map<String,String> translateMap(Map<String,Object> maps){
Map<String,String> ret = new HashMap<String, String>();
for(Map.Entry<
评论0
最新资源