john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

HTTP Post multipart form

// 2012-10-31 johnpfeiffer
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class POST
{
    private static final String CLASSVERSION = "0.22";
    private static final String CORRECTUSAGE = "Usage: java -jar POST-" + CLASSVERSION + ".jar http://example.com key1=value1&key2=value2";
    private static final String ENCODING = "UTF-8";
    private URL targetUrl;
    private String encodedQueries;
    private HttpURLConnection connection;
    private String response;

    public static void main( String[] args ) throws Exception
    {
        POST main = new POST();
        try
        {
            main.parseArguments( args );
        }catch( Exception e )
        {
            System.err.println( e.getMessage() );
            System.err.println( CORRECTUSAGE );
            System.exit( 1 );
        }
        System.out.println( "DEBUG: querying " + main.targetUrl + " for " + main.encodedQueries );
        main.PostQuery();
        System.out.println( main.getResponse() );
    }

    private void parseArguments( String[] args ) throws IllegalArgumentException
    {
        if( args.length != 2 )
        {
            throw new IllegalArgumentException( "ERROR: " + args.length + " is the wrong number of parameters" );
        }
        parseQueryInput( args[1] );
        initializeTargetUrl( args[0] );
    }

    private void parseQueryInput( String queryInput )
    {
        StringBuilder dataEncoded = new StringBuilder();
        String queryArray[] = queryInput.split( "&" );
        for( String query : queryArray )
        {
            if( dataEncoded.length() != 0 )
            {
                dataEncoded.append( "&" );
            }
            dataEncoded.append( parseQuery( query ) );
        }
        encodedQueries = dataEncoded.toString();
    }

    private String parseQuery( String query ) throws IllegalArgumentException
    {
        StringBuilder encodedQuery = new StringBuilder();
        String keyValue[] = query.split( "=" );
        if( keyValue.length != 2 )
        {
            throw new IllegalArgumentException( "ERROR: not in valid key=value format: " + query );
        }
        String key = keyValue[0];
        String value = keyValue[1];
        try
        {
            encodedQuery.append( URLEncoder.encode( key , ENCODING ) );
            encodedQuery.append( "=" );
            encodedQuery.append( URLEncoder.encode( value , ENCODING ) );
        }catch( UnsupportedEncodingException e )
        {
            throw new IllegalArgumentException( "ERROR: not in valid key=value format: " + query );
        }
        return encodedQuery.toString();
    }

    private void initializeTargetUrl( String targetUrlString )
    {
        try
        {
            // targetUrl = new URL( targetUrlString + "?" + encodedQueries );
            targetUrl = new URL( targetUrlString );
        }catch( MalformedURLException e )
        {
            throw new IllegalArgumentException( "ERROR: malformed URL: " + targetUrlString );
        }
        if( targetUrl == null )
        {
            throw new IllegalArgumentException( "ERROR: targetUrl cannot be null" );
        }
    }

    private void PostQuery() throws IllegalArgumentException , IOException
    {
        connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestProperty( "User-agent" , "JavaPost" );
        connection.setRequestProperty( "Accept" , "text/html" );
        connection.setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" );
        connection.setRequestProperty( "Content-Language" , "en-US" );
        connection.setRequestMethod( "POST" );
        connection.setRequestProperty( "Content-Length" , "" + Integer.toString( encodedQueries.getBytes().length ) );
        connection.setUseCaches( false );
        connection.setDoInput( true );
        connection.setDoOutput( true );

        // Send request
        DataOutputStream wr = new DataOutputStream( connection.getOutputStream() );
        wr.writeBytes( encodedQueries );
        wr.flush();
        wr.close();
        getPOSTResult();

    }

    private void getPOSTResult() throws IOException
    {
        if( connection != null )
        {
            StringBuilder strb = new StringBuilder();
            String newline = System.getProperty( "line.separator" );
            BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
            String line;
            while( ( line = in.readLine() ) != null )
            {
                strb.append( line + newline );
            }
            in.close();
            response = strb.toString();
        }
    }

    protected String getResponse()
    {
        return response;
    }

    private PostMultiPartFormRaw()
    {
            // Build upload URL and upload a file as a stream
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setScheme("https").setHost(uploadHost).setPath(UPLOAD).setParameter("uploadToken", uploadToken)
                .setParameter("destFolderPath", path).setParameter("metadata", metadata);

        URI uri = null;
        try
        {
            uri = uriBuilder.build();
        }
        catch (URISyntaxException e)
        {
            throw new SystemException("oxygencode=500" + e.getMessage());
        }

        String twoHyphens = "--";
        String boundary = "170062046428149";
        String lineEnd = "\r\n";
        String temp;

        URL url = uri.toURL();
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        // connection.setRequestProperty("Content-Type", "binary/octet-stream");
        connection.setRequestProperty("Content-Length", "" + contentLengthInBytes);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        OutputStream out = connection.getOutputStream();

        temp = twoHyphens + boundary + lineEnd;
        out.write(temp.getBytes());
        temp = "Content-Disposition: form-data; name=\"uploadToken\"" + lineEnd;
        out.write(temp.getBytes());

        temp = twoHyphens + boundary + lineEnd;
        out.write(temp.getBytes());
        temp = "Content-Disposition: form-data; name=\"destFolderPath\"" + lineEnd;
        out.write(temp.getBytes());

        temp = path + lineEnd;
        out.write(temp.getBytes());

        temp = twoHyphens + boundary + lineEnd;
        out.write(temp.getBytes());

        temp = "Content-Disposition: form-data; name=\"fileContent\";filename=\"" + filename + "\"" + lineEnd;
        out.write(temp.getBytes());
        temp = "Content-Type: binary/octet-stream" + lineEnd;
        out.write(temp.getBytes());

        temp = lineEnd;
        out.write(temp.getBytes());

        // write the data
        int bytesRead;
        byte[] buffer = new byte[10240]; // 1MB buffer
        while ((bytesRead = data.read(buffer)) != -1)
        {
            out.write(buffer, 0, bytesRead);
        }

        // send multipart form data necesssary after file data

        temp = lineEnd;
        out.write(temp.getBytes());

        temp = twoHyphens + boundary + twoHyphens + lineEnd;
        out.write(temp.getBytes());

        out.flush();
        out.close();

        // read the response
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        StringBuilder strb = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null)
        {
            strb.append(line + "\n");
        }
        System.out.println(strb.toString());

        if (out != null)
        {
            out.close();
        }
    }

    private void httpClientPost( URI uri , String filename , long contentLengthInBytes , InputStream data )
    {
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        multipartEntity.addPart("fileContent", new InputStreamBody(data, "binary/octet-stream", filename)
        {
            @Override
            public long getContentLength()
            {
                return contentLengthInBytes;    //otherwise always returns -1
            }
        });
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(multipartEntity);

        logger.debug("POSTING = " + uri.toString());

        HttpResponse httpResponse = httpclient.execute(httpPost);
        logger.debug("RESPONSE: " + httpResponse.getStatusLine().toString());
        String uploadResponse = EntityUtils.toString(httpResponse.getEntity(), "US-ASCII");
        logger.debug(uploadResponse);

        if (data != null)
        {
            data.close();
        }
    }

} // end class

  • « OxygenUploadCLI
  • threads logger log4j commandline parameters array to arraylist »

Published

Oct 31, 2012

Category

java-classes

~550 words

Tags

  • classes 92
  • form 20
  • http 12
  • java 252
  • multipart 2
  • post 12