view core/src/luan/modules/url/MultipartClient.java @ 725:a741a3a33423

add url support for multipart/form-data
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 08 Jun 2016 23:13:10 -0600
parents
children 14f136a4641f
line wrap: on
line source

package luan.modules.url;

import java.io.OutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import luan.LuanTable;
import luan.LuanException;


public final class MultipartClient {
	private static final byte[] __CRLF = {'\r','\n'};
	private static final byte[] __DASHDASH = {'-','-'};
	private static final String __ISO_8859_1 = "ISO-8859-1";

	private final Map params = new HashMap();

	MultipartClient(Map params) throws LuanException {
		for( Object hack : params.entrySet() ) {
			Map.Entry entry = (Map.Entry)hack;
			String key = (String)entry.getKey();
			Object val = entry.getValue();
			List list = new ArrayList();
			if( val instanceof String ) {
				list.add(val);
			} else {
				if( !(val instanceof LuanTable) )
					throw new LuanException( "parameter '"+key+"' must be string or table" );
				LuanTable t = (LuanTable)val;
				if( !t.isList() )
					throw new LuanException( "parameter '"+key+"' table must be list" );
				for( Object obj : t.asList() ) {
					if( !(obj instanceof String) )
						throw new LuanException( "parameter '"+key+"' values must be strings" );
					list.add(obj);
				}
			}
			this.params.put(key,list);
		}
	}

	public OutputStream write(HttpURLConnection httpCon) throws IOException {
		String boundary = "luan" + System.identityHashCode(this) + Long.toString(System.currentTimeMillis(),36);
		byte[] boundaryBytes = boundary.getBytes(__ISO_8859_1);

		httpCon.setRequestProperty("Content-Type","multipart/form-data; boundary="+boundary);
		OutputStream out = httpCon.getOutputStream();
		for( Object hack : params.entrySet() ) {
			Map.Entry entry = (Map.Entry)hack;
			String name = (String)entry.getKey();
			List list = (List)entry.getValue();
			for( Object obj : list ) {
				String val = (String)obj;
		        out.write(__DASHDASH);
		        out.write(boundaryBytes);
		        out.write(__CRLF);
//		        if (contentType != null)
//		            out.write(("Content-Type: "+contentType).getBytes(__ISO_8859_1));
//		        out.write(__CRLF);
	            out.write(("Content-Disposition: form-data; name=\""+name+"\"").getBytes(__ISO_8859_1));
	            out.write(__CRLF);
		        out.write(__CRLF);
				out.write(val.getBytes());
		        out.write(__CRLF);
			}
		}
		out.write(__DASHDASH);
		out.write(boundaryBytes);
		out.write(__DASHDASH);
		out.write(__CRLF);
		return out;
	}
}