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>