java后台如何调用别人接口传表单图片?

本文介绍了在Java后台如何使用RestTemplate和OkHttpClient调用HTTP接口,特别是涉及到表单数据和图片上传的场景。首先展示了使用Spring的RestTemplate通过设置HttpHeaders和MultiValueMap进行请求,然后演示了OkHttpClient的使用,创建RequestBody并构建表单数据进行POST请求。

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

java后台如何调别人的接口?http的有RestTemplate这款spring给的工具类,还有OkHttpClient的http请求客户端,那么我们就来介绍一下

1.使用RestTemplate调用别人的接口,以表单的形式传送图片

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;

public class HttpClienT {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送表单数据
     * @param jsonObject
     * @return
     */
    public void sendMessage(JSONObject jsonObject){
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("accept", "*/*");
            headers.add("connection", "Keep-Alive");
            headers.add("Accept-Charset", "utf-8");
            headers.add("Content-Type", "application/json; charset=utf-8");
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            FileSystemResource resource = new FileSystemResource(new File(jsonObject.getString("filePath")));
            param.add("TOKEN","1234");
            param.add("IMAGE",resource);
            param.add("FINAL",true);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> response  = restTemplate.exchange(jsonObject.getString("url"), HttpMethod.POST, requestEntity, JSONObject.class);
            System.out.println(response.getBody());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

2.使用OkHttpClient发送表单数据,带图片的

/**
 * 发送表单数据
 * @param jsonObject
 * @return
 */
public JSONObject sendMessage(JSONObject jsonObject){
    try {
        String requestUrl=jsonObject.getString("url");
        File file = new File(jsonObject.getString("filePath"));
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("TOKEN","1234")
                .addFormDataPart("IMAGE",file.getName(),
                        RequestBody.create(MediaType.parse("image/*"),
                                file))
                .addFormDataPart("FINAL","true")
                .build();
        Request request = new Request.Builder()
                .url(requestUrl)
                .method("POST", body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        Response response = client.newCall(request).execute();
        if (response.body() == null) {
            log.error("接口访问异常:"+requestUrl);
            return null;
        }
        return JSONObject.parseObject(response.body().string());
    }catch (Exception e){
        log.error("地刀识别失败",e);
        return null;
    }
}

在这之前要导入相关依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.14.9</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值