通过Apache的HttpClient来实现HTTP的GET方法(自定义URI)

本文档展示了如何使用Apache HttpClient库创建一个HttpGet请求,自定义URI,并处理响应。首先创建一个URIBuilder,设置协议、主机、路径和参数。然后,实例化HttpGet对象,并使用HttpClientBuilder构建的客户端执行请求。最后,打印出响应的HTTP版本、状态码、状态描述以及服务器返回的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.struts2.demo.httpclient;

import com.struts2.demo.utils.AvailableSettings;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeaderElementIterator;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by Frank on 2014/6/9.
 */
public class HttpGetDemo {
    private static Log logger = LogFactory.getLog(AvailableSettings.LOGNAME_TEST);

    public static void main(String[] args) {
        /**
         * 创建并实例化一个URI
         */
        URI uri = null;
        try {
            uri = new URIBuilder()
                    .setScheme("http")
                    .setHost("baike.baidu.com")
                    .setPath("/view/2476238.htm")
                    .setParameter("fr", "aladdin")
                    .build();
        } catch (URISyntaxException e) {
            logger.error("URISyntaxException,the detail is:" + e.getMessage());
        }

        /**
         * 创建一个HttpGet实例
         */
        HttpGet httpget = new HttpGet(uri);

        /**
         * 使用默认的上下文来执行Http的GET请求并获取响应内容
         */
        CloseableHttpResponse httpResponse = null;
        InputStream inputStream = null;
        try {
            httpResponse = HttpClientBuilder.create().build().execute(httpget);

            /**
             * 获取服务器端响应的HTTP版本号、状态码、状态描述
             */
            System.out.println(httpResponse.getProtocolVersion());
            System.out.println(httpResponse.getStatusLine().getStatusCode());
            System.out.println(httpResponse.getStatusLine().getReasonPhrase());
            System.out.println(httpResponse.getStatusLine());

            /**
             * 获取服务器端设置的Cookie信息
             */
            HeaderElementIterator it = new BasicHeaderElementIterator(httpResponse.headerIterator("Set-Cookie"));
            while (it.hasNext()) {
                HeaderElement headerElement = it.nextElement();
                System.out.println(headerElement.getName() + " = " + headerElement.getValue());
                NameValuePair[] params = headerElement.getParameters();
                for (NameValuePair param : params) {
                    System.out.println(" " + param);
                }
            }

            /**
             * 获取服务器端响应的内容
             */
            inputStream = httpResponse.getEntity().getContent();
            byte[] buffer = new byte[1024];
            StringBuilder sb = new StringBuilder(1024);
            while (inputStream.read(buffer) != -1) {
                sb.append(new String((buffer)));
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            logger.error("IOException,the detail exception:" + e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("inputStream.close exception:" + e.getMessage());
                }
            }
            try {
                if (null != httpResponse) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.error("httpResponse.close exception:" + e.getMessage());
            }
        }
        System.out.println(httpget.getURI());
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值