HttpClient如何进行表单提交呢?

java 文章 2022-07-23 11:40 995 0 全屏看文

AI助手支持GPT4.0

转自:

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

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

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

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

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


下文笔者讲述基于HttpClient Utils工具类编写一个表单提交的示例分享,如下所示:

HttpClient Utils进行表单提交同post提交的方式一摸一样,如下所示
实现思路:
    1.获取连接
	2.声明一个HttpPost
	3.创建请求参数体
	4.execute获取信息
	5.getEntity获取返回信息
	6.关闭连接
/** 
     * post方式提交表单(模拟用户登录请求) 
     */   
    public void postForm() {   
        // 创建默认的httpClient实例.     
        CloseableHttpClient httpclient = HttpClients.createDefault();   
        // 创建httppost     
        HttpPost httppost = new HttpPost("http://java265.com/login");   
        // 创建参数队列     
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();   
        formparams.add(new BasicNameValuePair("username", "admin"));   
        formparams.add(new BasicNameValuePair("password", "java265.compwd"));   
        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