今天用httpClient遇到一个问题,找了很久没找到问题在哪,用了另一种方法可以,但是这个问题还是没找到解决办法。具体如下:
首先客户端发送请求
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("format","1");
String s = doPost("http://localhost:9066/addRule", map);
System.out.println(s);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS * 10)
.build();
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json");
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
Iterator<Map.Entry<String, String>> it = param.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
paramList.add(basicNameValuePair);
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
return EntityUtils.toString(httpClient.execute(httpPost).getEntity(), "utf-8");
} catch (SocketTimeoutException e) {
log.warn("POST request read time out:", e);
throw SysException.of(SysException.NET_READ_TIME_OUT_EXCEPTION);
} catch (Exception e) {
log.error("POST request error:", e);
throw new RuntimeException("do post request error! " + e.getMessage());
}
}然后服务端接受
@Controller
public class a {
@ResponseBody
@PostMapping("/addRule")
public String addRule(@RequestBody @Valid AddRuleForm form) {
System.out.println(form.getFormat());
return "哈哈哈";
}
}
@Data
public class AddRuleForm implements Serializable {
@Min(1)
private String format;
}然后就会报这个错
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'format': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'format': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 8]]就不知道怎么办了
有没有大神知道怎么解决和原因呢