HttpClient如何进行post请求呢?

java-教程王 Java教程 发布时间:2022-04-19 14:39:49 阅读数:10313 1 HttpClient
下文笔者讲述基于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
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaCourse/202204/2936.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者