multipartEntityBuilder

multipartEntityBuilder

我正在尝试将文件以及一些变量上传到Web服务。根据我在网上阅读的内容,MultipartEntityBuilder将是完成这项工作的工具。但是,当我以描述的方式使用它时,post变量(文本和文件)似乎都不随查询一起发送。接收端的反应就像没有附加任何post变量一样。

我尝试通过使用以下代码将url指向文件来测试该理论:

<?php
$data = "";
foreach ($_POST as $key => $value) {
    $data = $data . "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
}
echo $data;
?>

并且该调用未返回任何数据(并且当我使用其他发布方法时也确实返回了数据。

有什么想法可能是什么问题吗?
The code in question:

        String url = "http://aktivthospital.dk.web1.aktivthospital.dk/index.php";

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "multipart/form-data");

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        entityBuilder.addPart("option", new StringBody("com_redtournament", contentType));
        entityBuilder.addPart("task", new StringBody("competition.apiServiceUploadImage", contentType));
        entityBuilder.addPart("username", new StringBody(_username, contentType));
        entityBuilder.addPart("password", new StringBody(_password, contentType));
        entityBuilder.addPart("comp_id", new StringBody(String.valueOf(_competitionId), contentType));
        entityBuilder.addPart("img_title", new StringBody(_title, contentType));
        File file = new File(_imagepath);
        entityBuilder.addPart("img_file",new FileBody(file));
        httpPost.setEntity(entityBuilder.build());

        HttpResponse response = httpClient.execute(httpPost);

最佳答案

因此,我设法使某些工作正常进行,我不确定您是否可以这样做,但值得其他人注意。对于背景,我试图过帐到詹金斯。

无论我多么努力,我都只能将文件添加到MultipartEntityBuilder。更糟糕的是(也许)是我太懒惰/自大,无法更改处理POST的方式,因此我必须想出一种方法,使它尽可能少地进行代码更改和重写。

我试过了.addPart(name, new StringBody(value, contentType)).addTextBody(name, value)
我尝试将参数添加为JSON,但是那也不起作用。最后,我记得最初让参数起作用的时候。我最终决定做出一些不同的决定,但是我能够将最初的成功与MultipartEntityBuilder结合起来以取得完全的成功。

如果我的POST包含文件,则使用MultipartEntityBuilder并像以前一样添加这些文件。但是,对于参数,我将它们添加到URI中。因此,例如,对我有用的是:

http://jenkins.url/.../buildWIthParameters?firstname=firstvalue&secondname=secondvalue

并且还将实体设置为具有文件。两者的结合奏效了。

现在,我知道我们有完全独立的,不相关的项目,但是我认为记录我的成功是值得的,如果没有其他原因,只是给您其他尝试。

关于java - MultipartEntityBuilder不发送任何发布变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22920790/

10-10 03:26