HttpClient如何进行表单提交呢?

java-教程王 Java教程 2022-04-19 14:52:49 11660 1 HttpClient
下文笔者讲述基于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();   
            }   
        }   
    } 
参考资料:http://www.java265.com/JavaCourse/202204/2934.html
版权声明

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

本文链接: http://www.Java265.com/JavaCourse/202204/2937.html

最近发表

热门文章

好文推荐

Java265.com

//www.java265.com

站长统计|USA-001

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者