package com.foc.fetcher;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;  
/* 
 * 利用HttpClient进行post请求的工具类 
 */  
public class HttpClientUtil {
    
    public static String doPost(String url,Map<String, Object> params){
        
        return HttpClientUtil.doPost(url, params, "UTF-8");
    }
    
    public static String doPost(String url,Map<String, Object> params,String charset){
        HttpClient httpClient = null;  
        HttpPost httpPost = null;
        try{  
            httpClient = HttpClients.createDefault();
            httpPost   = new HttpPost(url);  
            //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for(Entry<String, Object> param:params.entrySet()){
                
                list.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }  
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){
                    
                    return EntityUtils.toString(resEntity, charset);  
                }
            }  
        }catch(Exception ex){
            ex.printStackTrace();  
        }  
        return null;
    }  
}  