Skip to content

Instantly share code, notes, and snippets.

@gfrison
Created September 3, 2015 09:23
Show Gist options
  • Save gfrison/ef9d9f36151234cf7f14 to your computer and use it in GitHub Desktop.
Save gfrison/ef9d9f36151234cf7f14 to your computer and use it in GitHub Desktop.
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.Random;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import rx.Observable;
public class ConcatUpload
{
public static void main(String[] args) throws MalformedURLException
{
RxNetty.createHttpGet(
"http://docs.spring.io/spring-xd/docs/current-SNAPSHOT/reference/html/images/spring-xd-admin-ui-jobs-view" +
"-module" +
"" + "-details-button.png").flatMap(response -> {//
final String cType = response.getHeaders().getHeader("Content-Type");
final String cLength = response.getHeaders().getHeader("Content-Length");
String boundary = new Random().nextInt(99999) + "";
byte[] header = ("--" + boundary + '\n' + "Content-Disposition: form-data; name=\"file\"; " +
"filename=\"code\"\nContent-Type: " + cType + "\n\n").getBytes();
byte[] footer = ("\n\n--" + boundary + "--").getBytes();
HttpClientRequest<ByteBuf> post = HttpClientRequest.createPost("/post.php?dir=qwer");
post.getHeaders().add("Content-Length", Integer.valueOf(cLength) + header.length + footer.length);
post.getHeaders().add("Content-Type", "multipart/form-data; boundary=" + boundary);
post.withContentSource(Observable.just(Unpooled.copiedBuffer(header))//
.concatWith(response.getContent())
/*
it works with a given byte array:
.concatWith(Observable.just(Unpooled.copiedBuffer(new byte[Integer.valueOf(cLength)])))
*/
.concatWith(Observable.just(Unpooled.copiedBuffer(footer))));
return RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("posttestserver.com", 80).build().submit(post).flatMap(
yresp -> yresp.getContent().map(bytes -> bytes.toString(Charset.defaultCharset()))).collect(
StringBuilder::new, StringBuilder::append);
}).toBlocking().forEach(str -> System.out.println(str.toString()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment