Java使用HttpClient库发送请求

HttpClient介绍

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载和安装

下载地址
http://hc.apache.org/downloads.cgi

下载二进制文件后解压lib文件夹,将jar包复制粘贴到项目目录,右击add to Build Path.
关联源码到httpcomponents-asyncclient-4.1.1-src\httpcomponents-asyncclient-4.1.1\目录即可查看源码。

使用示例

    public static void post() {
        // 创建HttpClient实例对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建Post请求
        HttpPost httppost = new HttpPost(
                "http://localhost:8080/服务端/servlet/Login");

        // 创建参数列表
        List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
        formparams.add(new BasicNameValuePair("user", "lisi"));
        formparams.add(new BasicNameValuePair("pwd", "123456"));

        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) {

                    // 遍历Header
                    Header[] allHeaders = response.getAllHeaders();
                    for (Header h : allHeaders) {
                        System.out
                                .println(h.getName() + " : " + h.getValue());
                    }

                    // 打印正文
                    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();
            }
        }
    }

你可能感兴趣的:(java,apache,httpclient,http协议,库)