3

I have this to run this command which gives me right output and i want to emulate this in java using HttpUrlConnection(or any third party library)

curl http://localhost/myservice/ -v  -H 'Content-Type: multipart/form-data' -F 'file=@/home/xyz/abc.jpg' -F 'type=image' -F 'id=123'

The service accepts a file,a type and an id.

My current code looks like this-

    String urlToConnect = "http://localhost/myservice/";
    String boundary = Long.toHexString( System.currentTimeMillis() ); // Just generate some unique random value
    HttpURLConnection connection = (HttpURLConnection) new URL( urlToConnect ).openConnection();
    connection.setDoOutput( true ); // This sets request method to POST.
    connection.setRequestProperty( "Content-Type", "multipart/form-data; boundary="+boundary);
    PrintWriter writer = null;
    try
    {
    writer = new PrintWriter( new OutputStreamWriter( connection.getOutputStream(), "UTF-8" ) );

        writer.println( "--" + boundary );

        // -F type =1
        writer.println( "Content-Disposition: form-data; name=\"type\"" );
        writer.println( "Content-Type: text/plain; charset=UTF-8" );
        writer.println();
        writer.println( "image" );
        //writer.println( "--" + boundary );
        // -F id=1
        writer.println( "Content-Disposition: form-data; name=\"id\"" );
        writer.println( "Content-Type: text/plain; charset=UTF-8" );
        writer.println();
        writer.println( 123 );
        //writer.println( "--" + boundary );

        writer.println( "Content-Disposition: form-data; name=\"file\"; filename=\"abc.jpg\"" );
        writer.println( "Content-Type: image/jpeg;" );
        writer.println();
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader( new InputStreamReader( new FileInputStream(
                "/home/xyz/abc.jpg" ), "UTF-8" ) );
            for( String line; (line = reader.readLine()) != null; )
            {
                writer.println( line );
            }
        }
        finally
        {
            if( reader != null ) try
            {
                reader.close();
            }
            catch( IOException logOrIgnore )
            {
            }
        }


    }
    finally
    {
        if( writer != null ) writer.close();
    }

    // Connection is lazily executed whenever you request any status.
    int responseCode = ((HttpURLConnection) connection).getResponseCode();
    System.out.println( responseCode ); // Should be 200

    StringBuffer responseContent = new StringBuffer();
    BufferedReader rd = null;
    try
    {
        rd = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
    }
    catch( Exception e )
    {
        rd = new BufferedReader( new InputStreamReader( connection.getErrorStream() ) );
    }
    String temp = null;
    while( (temp = rd.readLine()) != null )
    {
        responseContent.append( temp );
    }

    System.out.println( "Response : " + responseContent );
}
faizan
  • 680
  • 1
  • 6
  • 15
  • 3
    So whats the error that you are getting? – Subir Kumar Sao Sep 27 '12 at 14:43
  • I am not getting the same response as in case of curl. the service is not mine. Please tell me what might be possibly wrong,I will try it out. – faizan Sep 27 '12 at 14:48
  • check with wireshark if you sending exactly same http headers – JIV Oct 01 '12 at 07:08
  • What's the difference between your response and the response in case of `curl`? It might be easier [if you call your curl command from within the java application](http://stackoverflow.com/questions/8496494/running-command-line-in-java), so you can use exactly your curl command. (Note that this will not be platform-independend) – Uooo Oct 01 '12 at 07:13
  • @JIV thanx for suggesting wireshark.I will check with it soon. – faizan Oct 01 '12 at 08:49
  • @w4rumy Sorry but i want to keep it platform independent. – faizan Oct 01 '12 at 08:50

2 Answers2

4

I have tried using apache httpClient for the same and now my code looks like

 HttpClient httpclient = new HttpClient();
    File file = new File( "/home/abc/xyz/solar.jpg" );

    // DEBUG
    logger.debug( "FILE::" + file.exists() ); // IT IS NOT NULL        
    try
    {
    PostMethod filePost = new PostMethod( "http://localhost/myservice/upload" );

    Part[] parts = { new StringPart( "type","image"),new StringPart( "id","1"), new FilePart( "file", file ) };
    filePost.setRequestEntity( new MultipartRequestEntity( parts, filePost.getParams() ) );

    // DEBUG


        int response = httpclient.executeMethod( filePost );
        logger.info( "Response : "+response );
        logger.info( filePost.getResponseBodyAsString());
    }
    catch( HttpException e )
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch( IOException e )
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Now then I am getting the correct response code.

faizan
  • 680
  • 1
  • 6
  • 15
2

First of all, you can not use a BufferedReader to read a jpeg image. This class is intended for reading text content only. You need to read raw bytes with FileInputStream and send them as is into the output stream you get from connection.getOutputStream(). No writers in between.

Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68