post请求application/x-www-form-urlencoded

发布时间 2023-05-05 15:40:03作者: 王权-18K
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate
import org.springframework.util.MultiValueMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.http.HttpEntity

public static String postWithParamsForString(String url, String authorization , String grant_type, String scope) { HttpHeaders headers = new HttpHeaders(); org.springframework.http.MediaType mediaType = org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED; headers.setContentType(mediaType); headers.add("Authorization", authorization); RestTemplate restTemplate=new RestTemplate(); MultiValueMap<String, String> forms= new LinkedMultiValueMap<String, String>(); forms.put("grant_type", Collections.singletonList(grant_type)); forms.put("scope", Collections.singletonList(scope)); HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(forms, headers); String body = restTemplate.postForObject(url, httpEntity, String.class); return body; }