如何开启你的第一个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(); } } } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。