HttpClient 使用
Http响应
// HTTP响应 @Test public void httpResponse() { HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "u are right"); System.out.println(response.getStatusLine().toString());// HTTP/1.1 200 u are right System.out.println(response.getProtocolVersion());// HTTP/1.1 System.out.println(response.getStatusLine().getStatusCode());// 200 System.out.println(response.getStatusLine().getReasonPhrase());// u are right // Working with message headers response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost"); response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\""); // Header[] hs = response.getHeaders("Set-Cookie"); response.getFirstHeader("Set-Cookie"); response.getLastHeader("Set-Cookie"); // 最有效的遍历Headers HeaderIterator it = response.headerIterator("Set-Cookie"); while (it.hasNext()) { System.out.println(it.next()); } }
Http请求
// HTTP请求 @Test public void httpRequest() throws URISyntaxException { URI uri = new URIBuilder() .setScheme("HTTP") .setHost("localhost:8080") .setPath("/user/login") .setParameter("username", "admin") .setParameter("password", "123456") .build(); HttpGet post = new HttpGet(uri); // HTTP://localhost:8080/user/login?username=admin&password=123456 System.out.println(post.getURI()); }
Post
/* post方式提交表单(模拟用户登录请求) */ @Test public void post() { // 创建HttpClient对象 try (CloseableHttpClient client = HttpClients.createDefault()) { // 创建HttpPost HttpPost httpPost = new HttpPost("http://localhost:8080/user/login"); // 创建参数队列 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "123456")); // 设置URL字符编码 // 一个实体可以是可重复的,这意味着它的内容可以被多次读取。这只适用于自包含的实体(如 ByteArrayEntity或 StringEntity) //StringEntity entity = new StringEntity("msg", ContentType.create("text/plain", Charsets.UTF_8)); /* HttpClient提供了几个类,可以用来通过HTTP连接有效地流出内容 这些类的实例可以与封闭实体的实体相关联 字符串,字节数组,输入流,和文件:StringEntity, ByteArrayEntity, InputStreamEntity,和 FileEntity。 注意InputStreamEntity不可重复,因为它只能从底层数据流读取一次。一般建议实现一个自HttpEntity包含的自定义类, 而不是使用泛型InputStreamEntity。 FileEntity可以是一个很好的起点。 */ UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, Consts.UTF_8); /* 通常建议让HttpClient根据正在传输的HTTP消息的属性选择最合适的传输编码 可以通过设置HttpEntity#setChunked()为true 来通知HttpClient首选块编码 HttpClient将仅使用此标志作为提示。使用不支持块编码的HTTP协议版本(例如HTTP / 1.0)时,此值将被忽略。 */ uefEntity.setChunked(true); // 设置实体 httpPost.setEntity(uefEntity); // 执行POST请求并处理返回值 try (CloseableHttpResponse response = client.execute(httpPost)) { HttpEntity entity = response.getEntity(); if (entity != null) { // 在某些情况下,可能需要不止一次阅读实体内容。在这种情况下,实体内容必须以某种方式进行缓冲,无论是在内存中还是在磁盘上 entity = new BufferedHttpEntity(entity); // HttpClient也带有这个EntityUtils类,它公开了几个静态方法来更容易地从实体读取内容或信息。而不是java.io.InputStream直接阅读 // 但是,EntityUtils除非响应实体来自受信任的HTTP服务器并且已知其长度有限,否则强烈建议不要使用它。 System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); } } } catch (IOException e) { e.printStackTrace(); } }
Get
@Test public void get() { // 创建HttpClient对象 try (CloseableHttpClient client = HttpClients.createDefault();) { // 创建HttpGet HttpGet httpget = new HttpGet("http://localhost:8080/user/list"); // 执行get请求并处理结果 try (CloseableHttpResponse response = client.execute(httpget);) { // 获取响应实体 HttpEntity entity = response.getEntity(); // 打印响应状态 System.out.println(response.getStatusLine()); if (entity != null) { // 打印响应内容长度 System.out.println("Response content length: " + entity.getContentLength()); // 打印响应内容 System.out.println("Response content: " + EntityUtils.toString(entity)); } } } catch (ParseException | IOException e) { e.printStackTrace(); } }
Jar
import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;