package com.bcxin.ins.third.build.yangguang.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class SendUtils {
	final Log logger = LogFactory.getLog(this.getClass());
	/**
	 * �˺�����ƽ̨���������http����,�����յ���Ӧ ����sendStr���м��ܱ���
	 * 
	 * @param url
	 * @param sendStr
	 * @return
	 * @throws Exception
	 */
	public static   String httpSendReceiverForUTF8(String url, String sendStr) throws Exception {
		
		String responseStr = "";
		byte[] iXMLData = null;
		
		try {
			// ����һ��HttpURLConnection
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(url)
			.openConnection();
			// System.out.println("------httpSendReceiver---��ʼ:   ");
			httpConnection.setRequestMethod("POST");
			httpConnection.setDoOutput(true);
			httpConnection.setDoInput(true);
			httpConnection.setAllowUserInteraction(true);
			httpConnection.setReadTimeout(120000);
			httpConnection.setConnectTimeout(120000);
			httpConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

			httpConnection.connect();
			
			// ��������
			OutputStream outputStream = httpConnection.getOutputStream();
			byte[] buffer = sendStr.getBytes("utf-8");// ƽ̨���ɵ�XML��

		/*	byte[] buffer2 =	JSON.toJSONBytes(sendStr);*/


			/*	byte[] buffer=jsonObj.;*/
			outputStream.write(buffer);
			outputStream.flush();
			outputStream.close();
			// ������������

			InputStream inputStream = httpConnection.getInputStream();
			BufferedInputStream input = null; // ������,���ڽ������������
			buffer = new byte[2048]; // ���ݻ�����
			int count = 0; // ÿ����������ʵ�����ݳ���
			ByteArrayOutputStream streamXML = new ByteArrayOutputStream(); // �������ݴ�Ŷ���
			try {
				input = new BufferedInputStream(inputStream);
				while ((count = input.read(buffer)) != -1) {
					streamXML.write(buffer, 0, count);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (input != null) {
					try {
						input.close();
					} catch (Exception f) {
						f.printStackTrace();
					}
				}
			}
			iXMLData = streamXML.toByteArray(); // �õ�һ��byte����,�ṩ��ƽ̨
			httpConnection.disconnect();
			responseStr = String.valueOf(iXMLData);

		} catch (Exception e) {

			responseStr = "<policy><isSucc>false</isSucc>"
					+ "<failCause></failCause><printFlag></printFlag></policy>";
			e.printStackTrace();
		}
		// Ϊ�˴����쳣,�����쳣��ʱ��Ҳ�ܷ�����Ϣ,�ʰ�responseStr�ַ������γɷ�д��try��catch��
		
		System.out.println("------SendUtils���յ�����:   " + responseStr);
		return responseStr;
	}
}
