public String httpTest(){ String url = "https://www.apiopen.top/weatherApi"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("city", "西安")); 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"); log.info(responseString); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
HTTP客户端调用天气预报
最新推荐文章于 2023-03-26 22:24:31 发布