-
哪位大神能告诉我怎么用 java 封装 get 和 post 请求
2020-07-24 10:55这里举例说一下post请求的封装,get请求类似
@Test public void f1(){ try { String url = "http://XXXXX:XXXX/futureloan/mvc/api/member/login"; HttpPost post = new HttpPost(url); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("mobilephone", 13455555555)); parameters.add(new BasicNameValuePair("pwd", e10adc3949ba59abbe56e057f20f883e)); parameters.add(new BasicNameValuePair("type", 1)); // entity为原生form表单格式,可以从请求中Content-Type: // application/x-www-form-urlencoded中获得 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters); post.setEntity(entity); // 创建一个客户端 CloseableHttpClient httpClient = HttpClients.createDefault(); //发送请求包 CloseableHttpResponse response = httpClient.execute(post); //获得响应体 HttpEntity respEntity = response.getEntity(); String respResult = EntityUtils.toString(respEntity); System.out.println(respResult); } catch (Exception e) { e.printStackTrace(); } }
封装的思路,抽取出不变的部分,提取出参数(需要变化的:比如url地址,请求参数)--此处补充说明:从上面可看出请求参数存放在List parameters 中,该依赖于httpClient,所以此处可换成HashMap,更具有通用性
private static String post(String url, Map<String, String> paramsMap) { String respResult = ""; try { // 生成post请求 HttpPost post = new HttpPost(url); if (paramsMap != null) { // 设置post请求参数--请求体中间 // 创建一个容器,将保存在HashMap中的参数保存到这个容器中 List<NameValuePair> paramsList = new ArrayList<>(); Set<String> keySet = paramsMap.keySet(); for (String key : keySet) { String value = paramsMap.get(key); paramsList.add(new BasicNameValuePair(key, value)); } // 创建一个原生form表单的请求体 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramsList); // 设置post请求体 post.setEntity(entity); } // 创建一个HTTP发送客户端 CloseableHttpClient httpClient = HttpClients.createDefault(); // 发数据包 CloseableHttpResponse response = httpClient.execute(post); // 获取响应体中的内容 HttpEntity respEntity = response.getEntity(); respResult = EntityUtils.toString(respEntity); return respResult; } catch (Exception e) { e.printStackTrace(); } return respResult; }
调用方法
@Test public void post() { // 1.请求地址 String url = "http://XXXXX:XXXX/lmcanon_web_auto/mvc/member/api/member/login"; // 3.设置post请求参数--请求体中间 // 创建一个容器,保存每个参数 HashMap<String,String> paramsMap=new HashMap<>(); paramsMap.put("mobilephone", 13555555555); paramsMap.put("pwd", e10adc3949ba59abbe56e057f20f883e); paramsMap.put("type", 1); //返回响应体 String respResult=HttpUtils.post(url, paramsMap); System.out.println(respResult); }