HttpClient如何进行post请求呢?
下文笔者讲述基于HttpClient Utils工具类编写一个post请求的示例分享,如下所示:
实现思路: 1.获取连接 2.声明一个HttpPost 3.创建请求参数体 4.execute获取信息 5.getEntity获取返回信息 6.关闭连接
/** * 发送post请求 */ public void post() { //创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); //创建httppost HttpPost httppost = new HttpPost("http://java265.com"); //创建参数队列 list<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("type", "house")); 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) { 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(); } } }参考资料:http://www.java265.com/JavaCourse/202204/2934.html
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。