简体   繁体   English

使用apache的httpclient库上传文件无效

[英]File upload using apache's httpclient library not working

This question is very similar to How to upload a file using Java HttpClient library working with PHP , but even MultipartEntity is not uploading the file correctly. 这个问题与如何使用与PHP一起使用的Java HttpClient库上载文件非常相似,但是即使MultipartEntity也无法正确上载文件。 Here is an MWE on the client side: 这是客户端的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();
    }
}

The contents of /tmp/HelloWorld' are HELLO WORLD`. /tmp/HelloWorld' are的内容/tmp/HelloWorld' are HELLO WORLD`。

Here is what index.php looks like: 这是index.php样子:

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

The output looks like this, which seems to imply that the file contents are sent into $_REQUEST and $_POST , rather than $_FILES 输出看起来像这样,这似乎意味着文件内容被发送到$_REQUEST$_POST ,而不是$_FILES

1
Array
(
    [file] => HELLO WORLD

)
Array
(
    [file] => HELLO WORLD

)
Array
(
)
Array
(
)

My guess is that I am doing something stupid in the client code, but I am not sure what it is. 我的猜测是我在客户端代码中做了一些愚蠢的事情,但是我不确定这是什么。

I dug into the PHP source code, and apparently a filename is required on the Content-Disposition line. 我研究了PHP源代码,显然在Content-Disposition行上需要一个filename Therefore, adding the following code, from this answer , in the client solves the problem. 因此,在客户端中从此答案中添加以下代码即可解决该问题。

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM