背景:
本人发送post请求,报错
{"result":"FAILED","timestamp":"1634171535020","errorMessage":"Content type 'application/xml;charset=UTF-8' not supported"}
看了下,请求头没问题的,另辟蹊径,用其他方式代替,暂时避免了这个问题的发生。
解决方式1:自己封装http的post请求
/** * @author hfl */ public class HttpUtil { private static final Logger log = LoggerFactory.getLogger(HttpUtil.class); private static final CloseableHttpClient httpClient; static { RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } public static String sendPostJson(String url, JSONObject msg) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("content-type", "application/json"); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 log.info("param:{}",msg); out.print(msg); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { log.error(e.getMessage(), e); } //使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }
使用
String s1 = HttpUtil.sendPostJson(addScheduleUrl, (JSONObject) JSON.toJSON(request));
成功返回。
解决方式2:使用resttemplate的exchange,指定请求头的content-Type
RestTemplate template = new RestTemplate(); URI uri = UriComponentsBuilder.fromUriString(addScheduleUrl).build().toUri(); // 自定义body实体类 String s3 = JSON.toJSONString(request); RequestEntity<String> requestEntity = RequestEntity.post(uri) .accept(MediaType.APPLICATION_JSON) .header("Content-Type", "application/json") .body(s3); ResponseEntity<String> exchange = restTemplate.exchange(requestEntity, String.class); String body = exchange.getBody(); System.out.println(JSON.parseObject(body).toJSONString());
返回正常结果:
大功告成!!!