package com.casic.missiles.core.util;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.poi.ss.formula.functions.T;

import java.io.IOException;

public class HttpClientUtils {
//private static final int timeoutHttp = configProperty.getInt("httpTimeOut");
private static final int timeoutHttp = 90000;
    public static String post(String uri, String body,String auth) {
	HttpClient client = new HttpClient();
	client.setTimeout(timeoutHttp);//6000
	PostMethod method = new PostMethod(uri);
	// for (Map.Entry<String, String> entry : headers.entrySet()) {
	method.addRequestHeader("Content-type",
		"application/json; charset=utf-8");
	method.addRequestHeader("Accept", "application/json");
	if (!auth.isEmpty()) {
//		Base64.decode(auth);
		method.addRequestHeader("Authorization", auth);
	}
	// method.setEntity(new StringEntity(jsonParam.toString(),
	// Charset.forName("UTF-8")));
	// method.setRequestHeader(entry.getKey(), entry.getValue());
	// method.setRequestHeader("Accept-Charset", "UTF-8");
	// }
	method.setRequestBody(body);
	try {
	    int statusCode = client.executeMethod(method);
	    if (statusCode == HttpStatus.SC_OK) {
		return new String(method.getResponseBody(), "UTF-8");
		// return method.getResponseBodyAsString();
	    }

	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return null;
    }

    public static String get(String uri,String auth) {
	HttpClient client = new HttpClient();
	client.setTimeout(timeoutHttp);
	GetMethod method = new GetMethod(uri);
	method.addRequestHeader("Content-type",
				"application/json; charset=utf-8");
	method.addRequestHeader("Accept", "application/json");
	if (ToolUtil.isNotEmpty(auth)){
		method.addRequestHeader("Authorization", auth);
	}
	try {
	    int statusCode = client.executeMethod(method);
	    if (statusCode == HttpStatus.SC_OK) {
		return method.getResponseBodyAsString();
	    }

	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return null;
    }



    public static void main(String[] args) throws Exception {

//		System.out.println(get(""));
//		String sGet = "http://www.uradiosys.com:8094/api/LocatingData/GetTagStatusByHostID?hostId=123";
//		System.out.println(get(sGet));

//		String sUri = "http://www.uradiosys.com:8094/api/Statistics/GetAreaInOutResult";
//		String sBody = "{\"dtFrom\": \"2017-01-01 12:00:00\",\"dtTo\": \"2017-01-01 12:00:00\"}";
//		System.out.println(post(sUri,sBody));
    }
}
