HttpClient如何进行post请求呢?

java 文章 2022-07-23 09:40 942 0 全屏看文

AI助手支持GPT4.0

转自:

http://www.java265.com/JavaCourse/202204/2936.html

HttpClient是一个java语言编写的包,

我们使用HttpClient可以非常方便的发送Http请求

它使基于Http协议请求内容变得非常简单

HttpClient是Apache Jakarta Common下的子项目 它里面封装了很多使用http协议访问的工具,可用于高效访问http


下文笔者讲述基于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();   
            }   
        }   
    }
-EOF-

AI助手支持GPT4.0