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()); } }
通过Apache的HttpClient来实现HTTP的GET方法(自定义URI)
最新推荐文章于 2025-05-02 11:32:06 发布