本人小白一个,不能保证博客中内容都准确,如果博客中有错误的地方,望各位多多指教,请指正。欢迎找我一起讨论
不管是什么方式进行提交,基于springboot 使用 RestTemplate,请先写RestTemplate 的 配置类
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate( ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
// 支持中文编码
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter( Charset.forName("UTF-8")));
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}
1、表单方式 restTemplate 通过@Autowired自动注入
HttpHeaders headers = new HttpHeaders( );
headers.setContentType( MediaType.APPLICATION_FORM_URLENCODED ); // 请求头 非文件表单提交
MultiValueMap< String, String > params = new LinkedMultiValueMap<>( );
params.add( "id" , id ); //请求体参数
HttpEntity< MultiValueMap< String, String > > httpEntity = new HttpEntity<>( params , headers );
//发送http请求
ResponseEntity< byte[] > responseEntity = this.restTemplate.postForEntity( url , httpEntity , byte[].class );
//获取响应体中的内容
byte[] responseEntityBody = responseEntity.getBody( );
System.out.println(new String( responseEntityBody ) );
2、 json方式提交 restTemplate 通过@Autowired自动注入
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
JSONObject param = new JSONObject();
param.put("id", id);
HttpEntity<String> formEntity = new HttpEntity<String>(param.toJSONString(), headers);
JSONObject result = restTemplate.postForObject(url, formEntity, JSONObject.class);
byte[] data = result.getObject( "result" , byte[].class );
System.out.println( new String( data, StandardCharsets.UTF_8 ) );