package jp.ac.kyutech.mns.ist.util;

import java.io.IOException;
import java.net.ConnectException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

public class Poster {
	public String post(Part[] parts, String url){
//		System.out.print("post - "+url);
		PostMethod post = new PostMethod(url);
		try{
			post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

			HttpClient client = new HttpClient();
			int status = client.executeMethod(post);
			if (status == 200){
//				System.out.println("Success.");
			} else {
//				System.out.println("Failed. ("+status+")");
			}

//			InputStream in = post.getResponseBodyAsStream();
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
			return post.getResponseBodyAsString();
//			final int LS = 1024;
//			int b = 0;
//			byte buf[] = new byte[LS];
//			while((b = in.read(buf, 0, buf.length)) != -1 ) {
//				baos.write(buf,0,b) ;
//			}
//			baos.close();
//			byte[] responseBody = baos.toByteArray();
//			return new String(responseBody);
		} catch(IOException e){
			e.printStackTrace();
		} catch(Exception e){
			e.printStackTrace();			
		} finally {
			post.releaseConnection();
		}
		return null;
	}
	public String get(String url) throws ConnectException {
//		System.out.print("get - "+url);
		
		HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
	    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
	    GetMethod get = new GetMethod(url.toString());
	    get.setFollowRedirects(true);
	    try {
			int iGetResultCode = client.executeMethod(get);
//			System.out.println("ResultCode: "+iGetResultCode);
		} catch (HttpException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	    try {
			return get.getResponseBodyAsString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
