在Java中,可以使用Apache HttpClient庫來實現form-data形式的文件上傳。下面是一個簡單的示例代碼:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
public class FileUploader {
public static void main(String[] args) throws IOException {
// 創建HttpClient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 創建HttpPost對象,并設置URL
HttpPost httpPost = new HttpPost("http://example.com/upload");
// 創建MultipartEntityBuilder對象,并設置文件和其他參數
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("path/to/file"), ContentType.MULTIPART_FORM_DATA, "filename");
builder.addTextBody("param1", "value1");
builder.addTextBody("param2", "value2");
// 將MultipartEntityBuilder構建的實體對象設置到HttpPost對象中
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 執行HttpPost請求,獲取響應
HttpResponse response = httpClient.execute(httpPost);
// 解析響應
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
// 關閉HttpClient
httpClient.close();
}
}
上面的示例代碼中,使用MultipartEntityBuilder
創建一個multipart/form-data實體,通過addBinaryBody
添加文件參數,通過addTextBody
添加其他參數。然后將該實體設置到HttpPost
對象中,最后使用HttpClient
執行請求并獲取響應。請根據實際情況修改URL、文件路徑和參數名。