Making HTTP post request (with an input type=“file”) from within Maven, using command line parameters if possible

后端 未结 2 1472
天命终不由人
天命终不由人 2021-01-27 06:38

I would like to convert this bash script:

#!/bin/bash
if ! [ $# == 2 ]; then
   echo Usage: update-module admin-password module-file
   exit 1
fi
if ! [ -f $2 ];         


        
相关标签:
2条回答
  • 2021-01-27 07:30

    Try the Exec Maven Plugin. You might want to just store the cookie in ${project.build.directory} instead of /tmp (and then you don't need to remove it.

    You can use any property name for the host you like, say host.name. You should set a default in the POM:

    <properties>
      <host.name>...</host.name>
    </properties>
    

    That can be overridden with -Dhost.name=... on the command line.

    0 讨论(0)
  • 2021-01-27 07:42

    Use GMaven to embed an inline Groovy Script, and use apache httpclient to implement the post request. Something like this:

    <plugin>
        <groupId>org.codehaus.groovy.maven</groupId>
        <artifactId>gmaven-plugin</artifactId>
        <dependencies>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.0.2</version>
            </dependency>
        </dependencies>
        <executions>
            <execution>
                <phase>generate-resources</phase>
                <goals>
                    <goal>execute</goal>
                </goals>
                <configuration>
                    <source><![CDATA[
    
                        import org.apache.http.HttpResponse;
                        import org.apache.http.client.HttpClient;
                        import org.apache.http.client.methods.HttpPost;
                        import org.apache.http.entity.InputStreamEntity;
                        import org.apache.http.impl.client.DefaultHttpClient;
    
                        String url = pom.properties['http.url'];
                        File file = new File(pom.properties['http.attachmentFile'])
                        HttpClient client = new DefaultHttpClient();
                        HttpPost post = new HttpPost(url);
                        InputStreamEntity entity = new InputStreamEntity(file.newInputStream());
                        post.setEntity entity;
                        HttpResponse response = client.execute(post);
    
                    ]]></source>
                </configuration>
            </execution>
        </executions>
    </plugin>
    

    This uses the maven properties http.url and http.attachmentFile that you can specify on the command line using the -D syntax or in a pom.xml file in a <properties> block. Obviously, you'd need to extend the functionality to what else your shell script is doing, but this should get you started.

    0 讨论(0)
提交回复
热议问题