httpcilent连接第三方接口请求(post,get)

1.导入jar包:

httpclient-4.3.1

httpclient-cache-4.3.1

httpcore-4.4.4

2.前端发送ajax请求后使用Spring注解获取请求,编写后台代码,用modelandview返回到前台,这里以请求/group/create为例:

@Controller("groupController")
@RequestMapping("/group")
public class GroupController {
@RequestMapping(value = "/create", method = RequestMethod.POST)//method = RequestMethod.GET
public ModelAndView groupCreate(
@RequestParam(required = true) String groupName,
@RequestParam(required = false) String groupDesc
) { 
int resultCode=-1;
String message="";
String data = "";
// 创建默认的httpClient实例
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httpPost,hostip为第三方提供的ip
HttpPost httpPost = new HttpPost("http://" + hostIp + "/group/create");
//创建httpGet写法,str为参数,去除httpPost的代码
//String str = "";
//HttpGet httpGet = new HttpGet("http://" + hostIp + "/group/del?"+str);
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
httpPost.addHeader("Connection", "Keep-Alive");

// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("groupName", groupName));
formparams.add(new BasicNameValuePair("groupDesc", groupDesc));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(uefEntity);
//发送请求,获得响应
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
// 调用接口返回的字符串
String responseString = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonResult = JSONObject.fromObject(responseString);
// 根据自己的格式来
resultCode = (Integer) jsonResult.get("resultCode");
message = (String) jsonResult.get("message");
data = (String)jsonResult.get("data");
}
} 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();
}
}
ModelAndView mv=new ModelAndView();
mv.addObject("resultCode", resultCode);
mv.addObject("message", message);
mv.addObject("data", data);
return mv;
}
                                                                                                                                                                                                                         

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值