发送http请求携带MultipartFile参数

本文介绍了如何在Java中使用ApacheHttpClient库发送一个带有文件附件的MultipartHTTPPOST请求,并处理服务器响应,包括设置accessToken头和解析返回的JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String url = "http://xxxxxxxxxxxxxxx";//服务端要调用的外部接口
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
    HttpPost httpPost = new HttpPost(url);

    File file = new File(address);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", file, ContentType.parse("image/jpeg"), file.getName());

    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);

    // 添加 'accessToken' 请求头 访问需要带token则携带token
    httpPost.setHeader("accessToken", accessToken);

    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        // 打印响应结果
        if (statusCode == HttpStatus.SC_OK) {
            Gson gson = new Gson();
            String resp = EntityUtils.toString(response.getEntity(), "utf-8");
            MyResponse myResponse = gson.fromJson(resp, MyResponse.class);
            System.out.println("status:" + statusCode);
            System.out.println("result:" + resp);
            return myResponse.result;
        }

        System.out.println(response.getStatusLine());
        HttpEntity responseEntity = response.getEntity();
        EntityUtils.consume(responseEntity);
    } finally {
        response.close();
    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        httpClient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return null;

//响应结果体

static class MyResponse {
    boolean success;
    String message;
    int code;
    long timestamp;
    String result;
}
后端post请求发送MultipartFile文件可以使用Spring框架提供的MultipartFile类来实现,具体步骤如下: 1. 在前端页面中,使用input标签的type属性设置为file,并且name属性设置为文件参数名。 2. 在后端Controller中,使用@RequestParam注解获取前端传递的MultipartFile类型参数。 3. 创建一个java.net.URL对象来表示请求的URL地址,使用java.net.HttpURLConnection对象发送post请求并设置请求头,请求体中传递文件内容。 4. 获取请求响应,对响应进行处理。 示例代码如下: ```java @PostMapping("/upload") @ResponseBody public String handleFileUpload(@RequestParam("file") MultipartFile file) { try { URL url = new URL("http://example.com/upload"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(("--" + "----WebKitFormBoundary7MA4YWxkTrZu0gW" + "\r\n").getBytes()); os.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getOriginalFilename() + "\"\r\n").getBytes()); os.write(("Content-Type: " + file.getContentType() + "\r\n").getBytes()); os.write("\r\n".getBytes()); os.write(file.getBytes()); os.write("\r\n".getBytes()); os.write(("--" + "----WebKitFormBoundary7MA4YWxkTrZu0gW" + "--" + "\r\n").getBytes()); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } else { return "File upload failed with HTTP error code: " + responseCode; } } catch (Exception e) { return "File upload failed with exception: " + e.getMessage(); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值