package com.winit.api.client;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;

import com.winit.api.model.RequestMsg;
import com.winit.api.util.SignUtil;

/**
 * 
 * @author kang.wang
 *
 */
public class ApiClient {
	
	public static final String CONTENTTYPE = "application/json";
	public static final String CHARSET = "UTF-8";
	
	/**
	 * 
	 * @param requestMsg
	 * @param url
	 * @param app_secret
	 * @return
	 */
	public String post(RequestMsg requestMsg,String url,String token){
		
		String sign = SignUtil.getSign(requestMsg,token);
		requestMsg.setSign(sign);
		
		return post(requestMsg,url);
	}
	
	/**
	 * 
	 * @param requestMsg
	 * @param url
	 * @return
	 */
	public String post(RequestMsg requestMsg,String url){
		String result = null;
		PostMethod post = null;
		try {
			String postData = JSONObject.fromObject(requestMsg).toString();
			StringRequestEntity entity = new StringRequestEntity(postData, CONTENTTYPE, CHARSET);
			
			post = new PostMethod(url);
			post.setRequestEntity(entity);
			
			HttpClient client = new HttpClient();
			client.setConnectionTimeout(10000);
			client.setTimeout(300000);
			int statusCode = client.executeMethod(post);
			
			if(statusCode == HttpStatus.SC_OK){
				result = IOUtils.toString(post.getResponseBodyAsStream());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(post != null){
				post.abort();
			}
		}
		return result;
	}
	
}
