HttpClient跨域请求post

Posted 喜东东

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient跨域请求post相关的知识,希望对你有一定的参考价值。

service层

@Override
public Map<String, Object> selectCurrentProgress(String branchesId,String businessId) throws Exception {
//用于结束返回映射结果
Map<String ,Object> map=new HashMap<String,Object>();
//用于判断是否返回成功
int result=0;
// 创建默认的httpClient实例. 
CloseableHttpClient httpclient = HttpClients.createDefault(); 
// 创建httppost 
HttpPost httppost = new HttpPost("请求地址"); 
// 创建参数队列 
List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 
formparams.add(new BasicNameValuePair("branchesId", branchesId));
formparams.add(new BasicNameValuePair("businessId", businessId));
UrlEncodedFormEntity uefEntity; 
try { 
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); 
httppost.setEntity(uefEntity); 
System.out.println("executing request " + httppost.getURI()); 
CloseableHttpResponse response = httpclient.execute(httppost); 
try { 
HttpEntity entity = response.getEntity(); 
if (entity != null) {
String jsonStr=EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObj=JSONObject.parseObject(jsonStr);
if(jsonObj.getInteger("Code")==0){
result=1;
JSONObject dataJSONObj=jsonObj.getJSONObject("Data");
Integer waitingNumber=dataJSONObj.getInteger("要在页面显示的参数1");
Integer remainderNumber=dataJSONObj.getInteger("要在页面显示的参数2");
String estimateWaitingTime=dataJSONObj.getString("要在页面显示的参数3");
map.put("waitingNumber", waitingNumber);
map.put("remainderNumber", remainderNumber);
map.put("EstimateWaitingTime", estimateWaitingTime);
}
System.out.println("--------------------------------------"); 
// System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); 
System.out.println("--------------------------------------"); 
}
} finally {
response.close(); 

} catch (ClientProtocolException e) { 
e.printStackTrace(); 
} catch (UnsupportedEncodingException e1) { 
e1.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
// 关闭连接,释放资源 
try { 
httpclient.close(); 
} catch (IOException e) { 
e.printStackTrace(); 


map.put("result", result);
return map;
}

 

Controller层

@RequestMapping("")
@ResponseBody
public Map<String, Object> selectCurrentProgress(String branchesId,String businessId){
Map<String, Object> map = new HashMap<String,Object>();
try {
map = keywordsService.selectCurrentProgress( branchesId, businessId);
} catch (Exception e) {
map.put("result", 1);
map.put("message", "异常");
e.printStackTrace();
}
return map;
}

以上是关于HttpClient跨域请求post的主要内容,如果未能解决你的问题,请参考以下文章

JAVA利用HttpClient进行POST请求(HTTPS)

JAVA利用HttpClient进行POST请求(HTTPS)

彻底解决跨域问题

跨域请求httpclient

Angular 5,httpclient,跨域请求被阻止

网站跨域解决方案有哪些