Java HttpClient操作

566 阅读1分钟

HttpClient操作简介

操作环境

Window10

Java1.8

测试url:httpbin.org

  1. 导入maven依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.1.3</version>
</dependency>
  1. HttpClient使用步骤

    创建HttpClient 初始化HttpGet或者是HttpPost 使用HttpClient实例的exectue方法 解析HttpResponse

  2. HttpGet使用

初始化URI 并设置参数

URI uri = new URIBuilder()
        .setHost("httpbin.org") //设置待访问的域名
        .setScheme("http")   // 设置访问模式 http  https
        .setPath("get")     // 设置访问路径
        .setCharset(StandardCharsets.US_ASCII) //设置字符集
        .build();

代码如下

package com.bilibili;

import Utils.WebUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
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;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.BasicHttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class HttpGetDemo {
    public static void main(String[] args) {
        try (CloseableHttpClient client = HttpClients.createDefault()){
            URI uri = new URIBuilder()
                    .setHost("httpbin.org")
                    .setScheme("http")
                    .setPath("get")
                    .setCharset(StandardCharsets.US_ASCII)
                    .build();
            HttpGet httpGet = new HttpGet(uri);
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair("data", "dd");
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            list.add(basicNameValuePair);
            httpGet.setEntity(new UrlEncodedFormEntity(list));
            System.out.println(httpGet.getUri());
            CloseableHttpResponse response = client.execute(httpGet);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                String responseBody = EntityUtils.toString(entity);
                System.out.println(responseBody);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } finally {

        }
    }
}

访问结果

http://httpbin.org/get
{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "gzip, x-gzip, deflate", 
    "Content-Length": "7", 
    "Content-Type": "application/x-www-form-urlencoded; charset=ISO-8859-1", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/5.1.3 (Java/1.8.0_342)", 
    "X-Amzn-Trace-Id": "Root=1-63666044-25c9a56f1bac9c383a140455"
  }, 
  "origin": "183.193.46.56", 
  "url": "http://httpbin.org/get"
}
  1. HttpPost使用 和Get不同的是Post需要设置请求体
BasicNameValuePair basicNameValuePair = new BasicNameValuePair("data", "dd");
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(basicNameValuePair);
httpGet.setEntity(new UrlEncodedFormEntity(list));

其余的和上面都是一样的