使用apache的httpclient库无法正常上传文件

时间:2013-12-19 04:18:14

标签: java php

此问题与How to upload a file using Java HttpClient library working with PHP非常相似,但即使MultipartEntity也未正确上传文件。这是客户端的MWE:

import java.io.*;
import java.util.*;

import org.apache.http.entity.mime.*;
import org.apache.http.client.*;
import org.apache.http.message.*;
import org.apache.http.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.*;
import org.apache.http.impl.client.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;



// Emulate the post behavior of curl in java except post a string.
// https://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily

public class Foo{

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
    // TODO: Fix and test this method.
    private static void PostData() throws Exception {
        String url = "http://localhost/index.php";
        DefaultHttpClient httpclient = new DefaultHttpClient();

        // create the post request.
        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity();

        ContentBody body = new FileBody(new File("/tmp/HelloWorld"),
                org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM);
        entity.addPart("file", body);
        httppost.setEntity(entity);

        // execute request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        InputStream stream = resEntity.getContent();

        System.out.println(response.getStatusLine());
        System.out.println(convertStreamToString(stream));

    }
    public static void main(String[] args) throws Exception {
        PostData();
    }
}

/tmp/HelloWorld' are HELLO WORLD`的内容。

以下是index.php的样子:

<?php
echo empty($_FILES); 
print_r($_REQUEST); 
print_r($_POST); 
print_r($_GET); 
print_r($_FILES); 
>?

输出看起来像这样,这似乎意味着文件内容被发送到$_REQUEST$_POST,而不是$_FILES

1
Array
(
    [file] => HELLO WORLD

)
Array
(
    [file] => HELLO WORLD

)
Array
(
)
Array
(
)

我的猜测是我在客户端代码中做了一些愚蠢的事情,但我不确定它是什么。

1 个答案:

答案 0 :(得分:2)

我挖掘了PHP源代码,显然filename行需要Content-Disposition。因此,在客户端中添加以下代码this answer可以解决问题。

    FormBodyPart customBodyPart = new FormBodyPart("file", body) {
            @Override
            protected void generateContentDisp(final ContentBody body) {
                StringBuilder buffer = new StringBuilder();
                buffer.append("form-data; name=\"");
                buffer.append(getName());
                buffer.append("\"");
                buffer.append("; filename=\"-\"");
                addField(MIME.CONTENT_DISPOSITION, buffer.toString());
            }
    };
    entity.addPart(customBodyPart);