传:
后台传
/**
* 不知道谁写的发送post请求,很好用
* @param url
* @param requestJson
* @return
* @throws Exception
*/
public static String sendPostJson(String url, String requestJson) throws Exception {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectionRequestTimeout(60000)
.setConnectTimeout(60000)
.build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
//设置post请求方式为JSON
httpPost.addHeader("Authorization", "Basic" + encryptBASE64("username", "password"));
StringEntity data = new StringEntity(requestJson, "UTF-8");
data.setContentType("application/json; charset=UTF-8");
httpPost.setEntity(data);
//发送post请求
response = closeableHttpClient.execute(httpPost);
if (response == null || response.getStatusLine() == null) {
throw new Exception("发送POST请求失败,返回结果为空!");
}
//返回状态是否200
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
//得到请求结果
HttpEntity entityRes = response.getEntity();
if (entityRes != null) {
String responsetData = EntityUtils.toString(entityRes, "UTF-8");
return responsetData;
}
} else {
throw new Exception("发送POST-JSON请求出错:" + response);
}
} catch (Exception e) {
throw new Exception("发送POST请求出现异常,"+e.getMessage());
} finally {
try {
// 关闭连接释放资源
if (response != null) {
response.close();
}
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
前台传:
$.ajax({
url: 'http://localhost:8080/demo/post',
type: "post",
contentType: "application/json",
dataType: 'JSONP',
async: false,
data:
{
word: 1234567
}
})
接收:controller接收,参数为HttpServletRequest(万能的)
@PostMapping("/post")
public String post(HttpServletRequest request) {
try {
//对于jsonp
//request.getParameterMap;
//String word = request.getParameter("word");
//对于httpclient的post数据流
InputStream inputStream = request.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String word = "";
for (String str = ""; (str = bufferedReader.readLine()) != null;
word = word + str) {
;
}
bufferedReader.close();
inputStream.close();
JSONArray jsonArray = JSONArray.fromObject(word);
List<Demo> demoList = JSONArray.toList(jsonArray,Demo.class);