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

大兔子大兔子 提交于 2019-12-02 08:15:45

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.

Brett Porter

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!