-
哪位大神能告诉我怎么用 java 封装 get 和 post 请求
2020-07-24 10:55/**以get的方法处理接口请求调用 * @param url * @param params * @return */ public static String doGet(String url,Map<String, String> params) { List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); // 取出所有参数 Set<String> keys = params.keySet(); // 通过循环将参数保存到lst集合 for(String name:keys) { String value = params.get(name); parameters.add(new BasicNameValuePair(name, value)); } String parameter = URLEncodedUtils.format(parameters, "UTF-8"); url+="?"+ parameter; HttpGet httpGet = new HttpGet(url); HttpClient httpClient = HttpClients.createDefault(); String result =""; try { HttpResponse httpResponse = httpClient.execute(httpGet); result =EntityUtils.toString(httpResponse.getEntity()); } catch (Exception e) { e.printStackTrace(); } return result; }
-
哪位大神能告诉我怎么用 java 封装 get 和 post 请求
2020-07-24 10:55*********************************************POST****************************************************** public static String doPost(String url,Map<String, String> params) { HttpPost httpPost = new HttpPost(url); // 取出map中所有的参数名 Set<String> keys = params.keySet(); String result =""; List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); // 通过循环将参数保存到lst集合 for(String name:keys) { String value = params.get(name); parameters.add(new BasicNameValuePair(name, value)); } try { httpPost.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8")); // 准备请求头数据 HttpClient httpClient = HttpClients.createDefault(); //创建客户端 HttpResponse httpResponse = httpClient.execute(httpPost); //发送请求 // 发起请求,获取接口响应信息 result = EntityUtils.toString(httpResponse.getEntity()); } catch (Exception e) { e.printStackTrace(); } return result; }