简体   繁体   English

POST请求在cURL中成功,但在Java中失败

[英]POST request succeeds in cURL but fails in Java

The following is a snippet for uploading files using PHP. 以下是使用PHP上传文件的代码段。 I am an Android developer and I want to upload a file. 我是一名Android开发人员,我想上传文件。 Which means I have to send a POST request to a URL that contains this script. 这意味着我必须将POST请求发送到包含此脚本的URL。

What is the parameter name that I should use if I want to upload a file? 如果要上传文件,应该使用什么参数名称?

PHP 的PHP

if (file_exists("upload/" . $_FILES["file"]["name"])) {
    echo $_FILES["file"]["name"] . " already exists. ";
} else {
    move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
    echo "https://some.site/upload/" . $_FILES["file"]["name"];
}

When I try cURL, the file is uploaded successfully but when I do it via Java, it fails. 当我尝试使用cURL时,文件已成功上传,但是当我通过Java进行上传时,它失败了。

cURL 卷曲

curl -F file=@call_me_now_2.wav http://some.site/upload/

Java Code Java代码

    File f = new File("call_me_now_11.wav");

    HttpPost filePost = new HttpPost("https://some.site/upload/");
    FileEntity fileEntity = new FileEntity(f, "audio/wav");
    filePost.setEntity(fileEntity);

    HttpClient client = new DefaultHttpClient();
    client.execute(filePost, new BasicResponseHandler() {

        @Override
        public String handleResponse(HttpResponse response)
                throws HttpResponseException, IOException {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();

            int c = 0;
            StringBuilder builder = new StringBuilder();
            while((c = content.read()) != -1) {
                builder.append((char) c);
            }
            System.out.println(builder.toString());

            return builder.toString();
        }
    });

Answered by this . 对此回答。 But nevertheless an explanation. 但是尽管如此,还是有一个解释。

One cannot read a binary file as done (as text). 一个人不能读完二进制文件(作为文本)。 That gives problems with line endings, nul characters, character encodings, and again making it binary. 这样就产生了行尾,空字符,字符编码以及再次使其变为二进制的问题。

One normally would get the InputStream, here content , and stream it out, without first reading all into memory. 通常情况下,无需先将所有content读入内存即可获取InputStream(此处为content )并将其流式传输出去。

import org.apache.commons.fileupload.util.Streams;

OutputStream out = response.getOutputStream();
Streams.copy(content, out, false);

Of course on posting a form with file upload, follow the mentioned answer. 当然,在发布带有文件上传的表单时,请遵循上述答案。

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

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