/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.jboss.netty.example.http.upload;
import java.io.File;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.QueryStringEncoder;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultHttpDataFactory;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.DiskAttribute;
import org.jboss.netty.handler.codec.http.DiskFileUpload;
import org.jboss.netty.handler.codec.http.InterfaceHttpData;
import org.jboss.netty.handler.codec.http.HttpPostRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpDataFactory;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.codec.http.HttpPostRequestEncoder.ErrorDataEncoderException;
/**
* @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
* @author Andy Taylor (andy.taylor@jboss.org)
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @author <a href="http://openr66.free.fr/">Frederic Bregier</a>
*
* @version $Rev$, $Date$
*/
public class HttpClient {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println(
"Usage: " + HttpClient.class.getSimpleName() +
" baseURI Filepath");
return;
}
String baseURI = args[0];
String postSimple, postFile, get;
if (baseURI.endsWith("/")) {
postSimple = baseURI+"formpost";
postFile = baseURI+"formpostmultipart";
get = baseURI+"formget";
} else {
postSimple = baseURI+"/formpost";
postFile = baseURI+"/formpostmultipart";
get = baseURI+"/formget";
}
URI uriSimple;
try {
uriSimple = new URI(postSimple);
} catch (URISyntaxException e) {
System.err.println("Error: "+e.getMessage());
return;
}
String scheme = uriSimple.getScheme() == null? "http" : uriSimple.getScheme();
String host = uriSimple.getHost() == null? "localhost" : uriSimple.getHost();
int port = uriSimple.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("http")) {
port = 80;
} else if (scheme.equalsIgnoreCase("https")) {
port = 443;
}
}
if (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
System.err.println("Only HTTP(S) is supported.");
return;
}
boolean ssl = scheme.equalsIgnoreCase("https");
URI uriFile;
try {
uriFile = new URI(postFile);
} catch (URISyntaxException e) {
System.err.println("Error: "+e.getMessage());
return;
}
File file = new File(args[1]);
if (! file.canRead()) {
System.err.println("A correct path is needed");
return;
}
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(new HttpClientPipelineFactory(ssl));
// setup the factory: here using a mixed memory/disk based on size threshold
HttpDataFactory factory = new DefaultHttpDataFactory(
DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE
DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
DiskFileUpload.baseDirectory = null; // system temp directory
DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
DiskAttribute.baseDirectory = null; // system temp directory
// Simple Get form: no factory used (not usable)
List<Entry<String,String>> headers =
formget(bootstrap, host, port, get, uriSimple);
if (headers == null) {
factory.cleanAllHttpDatas();
return;
}
// Simple Post form: factory used for big attributes
List<InterfaceHttpData> bodylist =
formpost(bootstrap, host, port, uriSimple, file, factory, headers);
if (bodylist == null) {
factory.cleanAllHttpDatas();
return;
}
// Multipart Post form: factory used
formpostmultipart(bootstrap, host, port, uriFile, file, factory, headers, bodylist);
// Shut down executor threads to exit.
bootstrap.releaseExternalResources();
// Really clean all temporary files if they still exist
factory.cleanAllHttpDatas();
}
/**
* Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
* due to limitation on request size).
* @return the list of headers that will be used in every example after
**/
private static List<Entry<String,String>> formget(ClientBootstrap bootstrap, String host, int port, String get,
URI uriSimple) {
// XXX /formget
// No use of HttpPostRequestEncoder since not a POST
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
// Wait until the connection attempt succeeds or fails.
Channel channel = future.awaitUninterruptibly().getChannel();
if (!future.isSuccess()) {
future.getCause().printStackTrace();
bootstrap.releaseExternalResources();
return null;
}
// Prepare the HTTP request.
QueryStringEncoder encoder = new QueryStringEncoder(get);
// add Form attribute
encoder.addParam("getform","GET");
encoder.addParam("info","first value");
encoder.addParam("secondinfo","secondvalue 锟斤拷锟?&");
// not the big one since it is not compatible with GET size
// encoder.addParam("thirdinfo", textArea);
encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
encoder.addParam("Send","Send");
URI uriGet;
try {
uriGet = new URI(encoder.toString());
} catch (URISyntaxException e) {
System.err.println("Error: "+e.getMessage());
bootstrap.releaseExternalResources();
return null;
}
HttpRequest request = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIStr