package cust.com.rac.integration;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class RequestServer {

	public static String request( String urlStr, String params ){
		String result = "";
		
		HttpURLConnection httpCon = getHttpConnection(urlStr);
		if(httpCon == null){
			return "Error:连接BPM失败!";
		}
		try {
			PrintWriter printWriter = new PrintWriter(httpCon.getOutputStream());
			printWriter.print(params);
			printWriter.flush();
			printWriter.close();
			
			InputStream inputStream = httpCon.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int i = 0;
			byte []array = new byte[1024];
			while( (i = inputStream.read(array)) != -1){
				out.write(array, 0, i);
			}
			result = new String(out.toByteArray(),"GBK");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			result = "Error:"+e.getMessage();
			e.printStackTrace();
		} 
		return result;
	}
	
	public static String sendFile( String urlStr, String filePathAndName ){
		
		String result = "";
		
		try {
			HttpURLConnection httpCon = getHttpConnection(urlStr);
			if(httpCon == null){
				return "Error:连接BPM失败!";
			}
			
			File file = new File(filePathAndName);
			if(!file.exists()){
				return "Error:文件不存在:"+filePathAndName;
			}
			String boundary = "----------Ef1ae0gL6GI3KM7Ef1ei4KM7cH2ae0";
			
			StringBuffer boundaryBefore = new StringBuffer("--").append(boundary).append("\r\n");
			boundaryBefore.append("Content-Disposition: form-data; name=\"Filename\"\r\n\r\n");
			boundaryBefore.append(file.getName()).append("\r\n").append("--").append(boundary).append("\r\n");
			boundaryBefore.append("Content-Disposition: form-data; name=\"Filedata\"; filename=\"").append(file.getName()).append("\"\r\n");
			boundaryBefore.append("Content-Type: application/octet-stream\r\n\r\n");
			
			StringBuffer boundaryAfter = new StringBuffer("\r\n--").append(boundary).append("\r\n");
	        boundaryAfter.append("Content-Disposition: form-data; name=\"Upload\"\r\n\r\n");
	        boundaryAfter.append("Submit Query\r\n").append("--").append(boundary).append("--\r\n");
	        
			byte[] boundaryBeforeBytes = boundaryBefore.toString().getBytes("UTF-8");
	        byte[] boundaryAfterBytes = boundaryAfter.toString().getBytes("UTF-8");
			
	        FileInputStream fis = new FileInputStream(filePathAndName);//用来读
	        int blockLen = fis.available();
	        System.out.println("blockLen="+blockLen);
	        byte dataBytes[] = new byte[blockLen]; 
	        fis.read(dataBytes);
	        fis.close();
	        
	        byte[] postBytes = new byte[boundaryBeforeBytes.length + dataBytes.length + boundaryAfterBytes.length];
	        System.arraycopy(boundaryBeforeBytes, 0, postBytes, 0, boundaryBeforeBytes.length);  
	        System.arraycopy(dataBytes, 0, postBytes, boundaryBeforeBytes.length, dataBytes.length); 
	        System.arraycopy(boundaryAfterBytes, 0, postBytes, boundaryBeforeBytes.length + dataBytes.length, boundaryAfterBytes.length); 
	        
			httpCon.setRequestProperty("User-Agent", "HttpUploadTester Console Application");
			httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
			OutputStream ots = httpCon.getOutputStream();
			DataOutputStream dataOut = new DataOutputStream(ots);
			dataOut.write(postBytes);
			dataOut.flush();
			dataOut.close();
//			PrintWriter printWriter = new PrintWriter(ots);
////			String sendStr = boundaryBefore.append("------test upload file--------").append(boundaryAfter).toString();
//			String sendStr = boundaryBefore.append(dataBytes).append(boundaryAfter).toString();
//			System.out.println("sendStr = "+sendStr);
//			printWriter.print(postBytes);//postBytes
//			printWriter.flush();
//			printWriter.close();
			
			InputStream inputStream = httpCon.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int i = 0;
			byte []array = new byte[1024];
			while( (i = inputStream.read(array)) != -1){
				out.write(array, 0, i);
			}
			result = new String(out.toByteArray(), "UTF-8");
//			System.out.println("result errMsg = "+result);
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			result = "Error:"+e.getMessage();
			e.printStackTrace();
		}catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			result = "Error:"+e.getMessage();
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			result = "Error:"+e.getMessage();
			e.printStackTrace();
		}
		return result;
	}
	public static HttpURLConnection getHttpConnection(String urlStr ){
		HttpURLConnection httpCon = null;
		
		try {
			URL url = new URL(urlStr);
			httpCon = (HttpURLConnection)url.openConnection();
			httpCon.setDoInput(true);
			httpCon.setDoOutput(true);
			httpCon.setUseCaches(false);
			httpCon.setDefaultUseCaches(false);
			httpCon.setRequestMethod("POST");
			httpCon.setConnectTimeout(30*1000);
			httpCon.setReadTimeout(30*1000);
		} catch(Exception er){
			er.printStackTrace();
		}
		return httpCon;
	}
}
