package com.foc.fetcher;

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

import com.alibaba.fastjson.JSONObject;
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);
            System.out.println("返回码:"+JSONObject.toJSONString(response.getStatusLine()));
            if(response != null){  
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    String resEntityStr = EntityUtils.toString(resEntity, charset);
                    System.out.println("resEntity ="+resEntityStr);
                    return resEntityStr;
                }else{
                    System.out.println("resEntity =响应体为空"+JSONObject.toJSONString(resEntity));
                }
            }  else{
                System.out.println("resEntity =响应为空"+JSONObject.toJSONString(response));
            }
        }catch(Exception ex){
            ex.printStackTrace();
            System.out.println("ex.getMessage() = " + ex.getMessage());
        }  
        return null;
    }

    public static void main(String[] args) {
        String s = doPost("https://qinqing.koalacloud.com:9010//laqzhyy-task/task/sewage/getRankData", new HashMap<String, Object>(), "UTF-8");
    }
}  