如何使用groovy中的文件进行http调用以上传文件并构建参数

时间:2015-11-21 06:08:12

标签: groovy jenkins

我可以让jenkins remote api request传递一个文件并使用cURL

对其进行处理
 curl http://server.com:8080/job/dummyJob/build -F file0=@/tmp/data  -F json='{"parameter": [{"name":"LIST","file":"file0"}, {"name":"SEARCH", "value":"Build"}, {"name":"LABEL", "value":"2015/11/20"}, {"name":"UPDATEDB", "value":"TRUE"}  ]}'

这样做的常规方法是什么? (以下java-ish代码)

@Grapes([
        @Grab(group = 'org.apache.httpcomponents', module = 'httpclient', version = '4.5.1'), 
         @Grab(group = 'org.apache.httpcomponents', module = 'httpmime', version = '4.5.1') 
])

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);


HttpPost httppost = new HttpPost("http://server.com:8080/job/dummyJob/build");

//need multipart ofrm submission
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)


String payLoad = '''{"parameter": [{"name":"LIST","file":"file0"}, {"name":"SEARCH", "value":"Build"}, {"name":"LABEL", "value":"2015/11/20"}, {"name":"UPDATEDB", "value":"TRUE"}  ]}'''
File file = new File("c:/payload.txt");



ContentBody cbFile = new FileBody(file, "text/txt");
ContentBody json = new StringBody(payLoad)


builder.addPart(new FormBodyPart("file0", cbFile)) //file0 is the name used in json data structure
builder.addPart(new FormBodyPart("json", json)) //all of the json content with name json


httppost.setEntity(builder.build());
HttpResponse response = httpclient.execute(httppost);

HttpEntity resEntity = response.getEntity();

1 个答案:

答案 0 :(得分:2)

试试这个,请告诉我是否有任何问题:

var newGame=0;
//joins new game (username,password)
app.post('/game/join', function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    if(newGame==1){
        res.send('Game Started');
        newGame=0;
    }
    else{
        newGame=1;
        wait(username, function(){
            res.send('Game Started'+username);
        });
    }
});

function wait(username){
    while(newGame==1){
        console.log(username + newGame);
    }
}