java http请求multipart/form-data数据,文本和附件
发布时间:
2024-03-20
预览次数:
以下是一个示例代码,演示了如何使用 Apache 的 HttpClient 发送包含文本和附件的 multipart/form-data 请求:
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.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import java.io.File;import java.io.IOException;public class MultipartFormDataExample { public static void main(String[] args) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("http://example.com/upload"); // 替换为你要发送请求的URL MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("key", "value", ContentType.TEXT_PLAIN); // 添加文本字段 builder.addBinaryBody("file", new File("path/to/file.txt"), ContentType.DEFAULT_BINARY, "file.txt"); // 添加文件 HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); // 处理响应内容 } } catch (IOException e) { e.printStackTrace(); } } }
在这个示例中,我们使用了 Apache HttpClient 的 MultipartEntityBuilder 来构建包含文本字段和文件的 multipart/form-data 请求。通过 addTextBody 方法添加文本字段,通过 addBinaryBody 方法添加文件。记得将"http://example.com/upload"
替换为实际的目标 URL,将"path/to/file.txt"
替换为实际的文件路径。