Mercurial Hosting > luan
view src/luan/modules/url/MultipartClient.java @ 941:c948f674a2d5
simplify Timeout
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 11 Oct 2016 00:34:19 -0600 |
parents | 1a68fc55a80c |
children | 668f29bc52ea |
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); 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; } }