如何使用Java HttpClient库与PHP一起工作上传文件

52

我想编写一个Java应用程序,将文件上传到使用PHP的Apache服务器。Java代码使用的是Jakarta HttpClient库的4.0 beta2版本:

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9002/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    FileEntity reqEntity = new FileEntity(file, "binary/octet-stream");

    httppost.setEntity(reqEntity);
    reqEntity.setContentType("binary/octet-stream");
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

这个PHP文件upload.php非常简单:

<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
  echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
  move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
  echo "Possible file upload attack: ";
  echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
  print_r($_FILES);
}
?>

阅读响应后,我得到以下结果:

executing request POST http://localhost:9002/upload.php HTTP/1.1
HTTP/1.1 200 OK
可能发生文件上传攻击:文件名为空。
Array
(
)
所以请求成功,我能够与服务器通信,但是 PHP 没有注意到文件 - 方法 is_uploaded_file 返回了 false$_FILES 变量为空。我不知道为什么会发生这种情况。我已经跟踪了 HTTP 响应和请求,它们看起来很正常:
请求如下:
POST /upload.php HTTP/1.1
Content-Length: 13091
Content-Type: binary/octet-stream
Host: localhost:9002
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.0-beta2 (java 1.5)
Expect: 100-Continue

˙Ř˙ŕ..... 其余二进制文件...
响应如下:
HTTP/1.1 100 Continue

HTTP/1.1 200 OK
Date: Wed, 01 Jul 2009 06:51:57 GMT
Server: Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 mod_jk/1.2.26
X-Powered-By: PHP/5.2.5
Content-Length: 51
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
可能发生文件上传攻击:文件名为空。Array ( )
我在本地 windows xp 上使用 xampp 和远程 Linux 服务器进行了测试。我也尝试使用先前的 HttpClient 版本 - 版本 3.1 - 结果更不清晰,is_uploaded_file 返回 false,但是 $_FILES 数组中包含正确的数据。

DefaultHttpClient()现在已经被弃用。 - Pranjal Choladhara
@PranjalCholadhara 那么在 DefaultHttpClient() 被弃用之后,应该使用哪个类? - Pruthvi Chitrala
10个回答

66

好的,我之前使用的Java代码是错误的,这里提供正确的Java类:

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

请注意使用MultipartEntity。


1
这个受支持的 HttpComponents (即 hc.apache.org 而不是 HttpClient-3.1)有哪些新的版本?我收到了错误信息:“无法解析类型 org.apache.james.mime4j.message.SingleBody。它是从所需的 .class 文件间接引用的。” - therobyouknow
2
答案:从http://hc.apache.org/downloads.cgi下载HttpClient 4.1-alpha1和HttpCore 4.1-alpha1 - 支持的Apache HttpComponents Java代码。使用它们,该错误消息就会消失 :) - therobyouknow
我正在使用4.2版本,但是我没有mime包。它被更改了吗? - expert
2
Apache HttpComponents MIME 功能可以在 group:artifact org.apache.httpcomponents:httpmime 中找到。 - Jacob Zwiers

30

对于那些尝试使用MultipartEntity的人,这里有一个更新...

org.apache.http.entity.mime.MultipartEntity在4.3.1版本中已经被弃用。

您可以使用MultipartEntityBuilder来创建HttpEntity对象。

File file = new File();

HttpEntity httpEntity = MultipartEntityBuilder.create()
    .addBinaryBody("file", file, ContentType.create("image/jpeg"), file.getName())
    .build();

对于Maven用户,该类可在以下依赖项中使用(与fervisa的答案几乎相同,只是版本稍后)。

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.3.1</version>
</dependency>

也许你应该更新已接受的答案并加以改进。 - Halil

3

我遇到了同样的问题,发现httpclient 4.x需要文件名才能与PHP后端配合使用。而httpclient 3.x则不需要。

所以我的解决方案是在FileBody构造函数中添加一个name参数。 ContentBody cbFile = new FileBody(file, "image/jpeg", "文件名");

希望这可以帮助你。


谢谢你的帮助。那真是救了我。但应该使用的构造函数是需要四个参数的那一个。new FileBody(file,file.getName(),"application/octet-stream","UTF-8"); 三个参数的构造函数将文件名作为第三个参数,而不是MIME类型。 - MTilsted

3

我尝试使用您提出的方法,即HttpClient v. 3.1,但仍然返回false,而这次$_FILES数组填充了正确的数据,这让我更加困惑。顺便说一句,上传在服务器上是有效的,我使用简单的HTML表单测试了我的upload.php文件。 - Piotr Kochański

2

这里有一个更新的版本示例。

以下是原始代码副本:

/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package org.apache.http.examples.entity.mime;

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                    "/servlets-examples/servlet/RequestInfoExample");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}

1
啊,你只需要在

标签中添加一个name参数。
FileBody constructor. ContentBody cbFile = new FileBody(file, "image/jpeg", "FILE_NAME");

希望它有所帮助。

1

我知道我来晚了,但以下是正确处理此问题的方法,关键是使用InputStreamBody代替FileBody上传多部分文件。

   try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("https://someserver.com/api/path/");
        postRequest.addHeader("Authorization",authHeader);
        //don't set the content type here            
        //postRequest.addHeader("Content-Type","multipart/form-data");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);


        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        reqEntity.addPart("parm-name", new InputStreamBody(fileInputStream,"image/jpeg","file_name.jpg"));

        postRequest.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(postRequest);

        }catch(Exception e) {
            Log.e("URISyntaxException", e.toString());
   }

1
这是我用Apache HTTP库发送图片的工作解决方案(非常重要的是添加边界,否则我的连接无法正常工作):
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] imageBytes = baos.toByteArray();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);

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

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

            ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
            StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
            StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);

            HttpEntity entity = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setBoundary(boundary)
                    .addPart("group", sbGroup)
                    .addPart("owner", sbOwner)
                    .addPart("image", bab)
                    .build();

            httpPost.setEntity(entity);

            try {
                HttpResponse response = httpclient.execute(httpPost);
                ...then reading response

0

对于那些在实现被接受的答案(需要org.apache.http.entity.mime.MultipartEntity)时遇到困难的人,可能正在使用org.apache.httpcomponents 4.2.*。在这种情况下,您必须明确安装httpmime依赖项,例如我的情况:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.5</version>
</dependency>

0

如果您正在本地WAMP上进行测试,则可能需要设置用于文件上传的临时文件夹。您可以在PHP.ini文件中完成此操作:

upload_tmp_dir = "c:\mypath\mytempfolder\"

您需要授予文件夹权限以允许上传 - 您需要授予的权限因操作系统而异。


临时文件夹已经设置好了。在服务器上上传功能正常,我已经用简单的HTML表单测试了我的upload.php文件。 - Piotr Kochański
请问您能告诉我如何编写Java服务器代码以接收HttpClient请求吗? - Aswan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接