首页 >Java >java教程 >如何使用 HttpClient 将文件从 Java 上传到 PHP 服务器?

如何使用 HttpClient 将文件从 Java 上传到 PHP 服务器?

Barbara Streisand
Barbara Streisand原创
2024-12-07 20:09:12426浏览

How to Upload a File from Java to a PHP Server Using HttpClient?

如何使用 HttpClient 库将文件从 Java 上传到 PHP 服务器

在本指南中,我们将探索如何上传文件使用 Jakarta HttpClient 库版本 4.0 将文件从 Java 应用程序传输到运行 PHP 的 Apache 服务器beta2.

Java 代码

下面的 Java 代码演示了如何使用 HttpClient 库上传文件:

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.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();
  }
}

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

疑难解答

如果文件未成功上传,请确保:

  • 文件未上传太大,服务器无法处理。
  • 正在使用正确的内容类型发送 HTTP 请求,例如作为“image/jpeg”。
  • PHP 代码正确处理上传的文件。

以上是如何使用 HttpClient 将文件从 Java 上传到 PHP 服务器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn