如何开启你的第一个httpClient程序呢?

颜丹晨 Java教程 发布时间:2022-05-08 22:07:35 阅读数:7685 1 HttpClient
下文笔者讲述第一个HttpClient程序的开发示例分享,如下所示:
实现思路:
    1.创建一个HttpClient
	2.定义一个httpRequest
	3.HttpClient.execute(request)
	4.获取httpClient运行后的结果
例:
package com.java265.other.httpClient;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;

public class HttpClient01 {
	/*
	 * java265.com 第一个HttpClient示例
	 */
	public static void main(String[] args) throws Exception {

		try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
			HttpGet httpGet = new HttpGet("http://www.java265.com");

			InputStream in = null;
			ByteArrayOutputStream bos = new ByteArrayOutputStream();

			try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
				System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
				HttpEntity entity1 = response1.getEntity();
				in = entity1.getContent();
				byte[] buffer = new byte[1024];
				int len = -1;
				while ((len = in.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				
				System.out.println("output:" + bos.toString());

			}catch(Exception e) {
				System.out.println("message:" + e.getMessage());
			}finally {
				 if(null != in) {
						in.close();
				 }
				 
				 if(null != bos) {
						bos.close();
				 }
			}
		}
	}

}
版权声明

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

本文链接: https://www.Java265.com/JavaCourse/202205/3307.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者