注入RestTemplate
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
1、get请求:
public static String doGet(String url, String token) {
log.info("http请求:" + url);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
JSONObject response = null;
get.addHeader("token", token);
try {
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(3000).build();
get.setConfig(requestConfig);
HttpResponse res = client.execute(get);
log.info("http响应code:" + res.getStatusLine().getStatusCode());
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.parseObject(result);
log.info("http响应结果:" + response);
return response.toString();
} catch (Exception e) {
log.error("接口请求异常", e);
}
return "";
}
2、post请求
public static JSONObject httpPost(String url, JSONObject json, String token) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
JSONObject response = null;
// Create a header for the authorization token
post.addHeader("token", token);
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");//解决中文乱码问题
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
3、文件上传(form_data)
public String fileUpload(Path filePath, String token) {
try {
String url = host + "/api"; // 替换为实际的API地址
// 创建请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("token", token);
// 创建请求体
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
// 添加文件参数
FileSystemResource file = new FileSystemResource(filePath); // 本地文件路径
body.add("file", file);
// 创建HTTP请求实体
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
try {
// 发送POST请求
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
// 请求成功,可以处理响应数据
JSONObject responseBody = JSONObject.parseObject(response.getBody());
if (response.getStatusCodeValue() == HttpStatus.SUCCESS) {
JSONArray dataArray = responseBody.getJSONArray("data");
if (dataArray != null && dataArray.size() > 0) {
return dataArray.getString(0);
} else {
return null;
}
} else {
return null;
}
} else {
return null;
}
} catch (Exception e) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
4、form_data传字段
public void fileUpload(String name) {
try {
String url = host + "/api";
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 创建表单数据
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("name", name);
// 创建HTTP请求实体
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
// 发送POST请求
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
String.class
);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}