无法使用HttpClient POST请求上传文件

时间:2016-04-04 08:33:57

标签: java http post file-upload httpclient

我有一个JSP页面(/Test/faces/pages/admin/csvImport.jsp),它有一个表单和一个输入文件类型File uploader。单击“上载”按钮后,表单将提交到自我URL /Test/faces/pages/admin/csvImport.jsp并上传文件。我想自动化这个文件上传,因此我使用HttpClient API来获取文件并提交表单。我正在尝试使用HttpClient API通过POST请求上传CSV文件,但不知何故文件没有上传。以下是执行上传的代码段:

        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

        HttpPost httpPost = new HttpPost("http://localhost:9088/Test/faces/pages/admin/csvImport.jsp");
        httpPost.setHeader("Cookie", "JSESSIONID="+ sessionId);
        String boundary = "---------------------------" + System.currentTimeMillis();

        httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+boundary);

        File file = new File("C:\\root\\projects\\DataSources1.csv");
        FileBody fileBody = new FileBody(file); 
        StringBody importBody = new StringBody("Import", ContentType.TEXT_PLAIN);
        StringBody csvImportFormBody = new StringBody("csvImportForm", ContentType.TEXT_PLAIN);
        StringBody uniqueTokenBody = new StringBody("j911", ContentType.TEXT_PLAIN);
        StringBody uniqueViewBody = new StringBody("j911", ContentType.TEXT_PLAIN);

        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();

        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.setBoundary(boundary);
        multipartEntity.addPart("uploadFileName", fileBody);
        multipartEntity.addPart("csvimportForm:ImportButton", importBody);
        multipartEntity.addPart("csvImportForm", csvImportFormBody);
        multipartEntity.addPart("uniqueToken", uniqueTokenBody);
        multipartEntity.addPart("uniqueView", uniqueViewBody);

        httpPost.setEntity(multipartEntity.build());
        HttpResponse response = httpClient.execute(httpPost,localContext);

我想在java代码中模拟的原始HTML表单是:

<form id="csvImportForm" method="post" action="/Test/faces/pages/admin/csvImport.jsp" enctype="multipart/form-data">
    <tr>
        <td width="25%" class="trayheader">
            <!-- "File Name" (label) --> <span id="csvImportForm:fileNameTitleId">File Name:</span></td>
        <td width="50%">
            <!-- File Selection (input) --> <input type="file" name="uploadFileName" style="width: 90%"></td>
        <td width="25%">
            <!-- Import (button) --> <input type="submit" value="Import" name="csvImportForm:importButton" id="csvImportForm:importButton" onclick="javascript:hideForm();" class="commandExButton" /></td>
    </tr>
    <input type="hidden" name="csvImportForm" value="csvImportForm" /><input type="hidden" name="csvImportForm:_idcl" /><input type="hidden" name="clickedLogoutLink" />
</form>

任何人都可以提供任何提示,为什么文件没有上传?当我执行代码时,它只是获取jsp页面而不上传文件。

比较HEADERS和POST参数后

UPDATE: 比较标题和参数。 使用FORM,它是:

Request               POST /Test/faces/pages/admin/csvImport.jsp HTTP/1.1
Accept  */*
Referer                https://host1:30862/Test/faces/pages/admin/csvImport.jsp
Accept-Language             en-GB
User-Agent         Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Content-Type    multipart/form-data; boundary=---------------------------7e0212b90428
Accept-Encoding              gzip, deflate
Host       host1:30862
Content-Length                2398
DNT       1
Connection        Keep-Alive
Cache-Control   no-cache
Cookie  ssoLang=en; dbihybrid_preferredLanguage=en; dbihybrid_locationDepartment=in.false; wt_eid=2143773288100110717; JSESSIONID=W9vmLJRZkf7u2Pevmd4QdSC2hUvliVepaVm-tFuz9m7O4lkWYPUw!1008091679; PA.MinLogLevel=30

与HTTPClient和它是:

Cookie: JSESSIONID=9C_m5OE8QUquA9sdj4T5eOyVS1yXC6yb0jdiVCuaZ_X-MjPQqEMw!1008091679
Content-Type: multipart/form-data; boundary=---------------------------1459867674444
Accept-Language: en-US,en;q=0.5
Accept: */*
Cache-Control: no-cache
Referrer: https://host1:30862/Test/faces/pages/admin/csvImport.jsp
Content-Length: 2423
Host: host1:30862
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.1 (java 1.5)
Accept-Encoding: gzip,deflate

带有FORM的POST参数:

Content-Disposition: form-data; name="csvImportForm" value="csvImportForm"
Content-Disposition: form-data; name="uniqueToken" value=""
Content-Disposition: form-data; name="uniqueView" value="j1154"
Content-Disposition: form-data; name="csvImportForm:importStatus" value=""
Content-Disposition: form-data; name="clipboard_l" value=""
Content-Disposition: form-data; name="clipboard_t" value=""
Content-Disposition: form-data; name="uploadFileName"; filename="C:\Users\Public\Documents\eclipse luna\workspace\WebScrapper\properties\DataSources.csv" Content-Type: application/vnd.ms-excel
Content-Disposition: form-data; name="csvImportForm:importButton" value="Import"
Content-Disposition: form-data; name="javax.faces.ViewState" value="3514046226787645214:-6068281828613739341"

使用HttpClient的POST参数:

Content-Disposition: form-data; name="uploadFileName"; filename="C:\Users\Public\Documents\eclipse luna\workspace\WebScrapper\properties\DataSources.csv" Content-Type: application/vnd.ms-excel; charset=UTF-8
Content-Disposition: form-data; name="csvImportForm:importButton" value="Import"
Content-Disposition: form-data; name="csvImportForm" value="csvImportForm"
Content-Disposition: form-data; name="uniqueToken" value="j1228"
Content-Disposition: form-data; name="uniqueView" value="j1228"
Content-Disposition: form-data; name="javax.faces.ViewState" value="8959970480121731339:-7418251671370896640"
Content-Disposition: form-data; name="clipboard_l" value=""
Content-Disposition: form-data; name="clipboard_t" value=""
Content-Disposition: form-data; name="csvImportForm:importStatus" value=""

1 个答案:

答案 0 :(得分:0)

在您的情况下不确定是否存在问题,但MultipartEntityBuilder在内部处理 Content-Type 标头和边界,因此您无需明确设置它们。也就是说,您可以安全地删除以下行

    String boundary = "---------------------------" + System.currentTimeMillis();

    httpPost.setHeader("Content-Type", "multipart/form-data; boundary="+boundary);
否则他们可能会相互冲突。

由于您只是设置随机的边界,您可以让MultipartEntityBuilder为您完成。如果您不提供边界,这是默认行为。你也可以删除

    multipartEntity.setBoundary(boundary);